Javascript 模拟函数 return 可读

Javascript Mocking functions that return Readable

我有一个调用我的 s3 服务的简单函数,它将 return 一个 Promise

  downloadFile(fileName: string): Promise<Readable> {
    console.log(
      "Downloading an object with key - ",
      fileName
    );

    return this.s3service.getObject(fileName);
  }

我想模拟对象的 return 并像这样在测试中声明它:

it("should return readable if file present", async () => {
  const readable = new Readable();
  readable.push("test");

  jest
    .spyOn(s3service, "getObject")
    .mockImplementation(() => Promise.resolve(readable));

  const file = await someService.downloadFile(
    TestConstants.reportName
  );

  expect(file).toBe(readable);
});

当我运行测试时,我遇到这个错误:

Error [ERR_METHOD_NOT_IMPLEMENTED]: The _read() method is not implemented at Readable.read (internal/streams/readable.js:642:9) at Readable.read (internal/streams/readable.js:481:10) at maybeReadMore (internal/streams/readable.js:629:12) at processTicksAndRejections (internal/process/task_queues.js:82:21) { code: 'ERR_METHOD_NOT_IMPLEMENTED'

想要一些关于如何正确模拟可读文件的帮助,例如在这个例子中

您的生产代码只是将来自服务的响应转发到外部,然后只是模拟 getObject 到 return 任何东西,并期望结果应该是 getObject 结果并且服务功能将使用正确的参数调用:

it("should return readable if file present", async () => {
  const readable = "readable-object" as unknown as Readable;
  jest.spyOn(s3service, "getObject").mockResolvedValue(readable);

  const actual = await someService.downloadFile(TestConstants.reportName);

  expect(actual).toBe(readable);
  expect(s3service.getObject).toHaveBeenCalledWith(TestConstants.reportName);
});