Jest 中的单元测试异步生成器函数

Unit test asynchronous generator function in Jest

我想为生成器函数编写单元测试,但我无法传递正确模拟的读取流 (ReadStream) 对象。

可测试函数:

  public async *readChunks(file: string, chunkSize: number): AsyncIterableIterator<Buffer> {
    if (!this.cwd) throw new Error('Working directory is not set!');

    const readStream: ReadStream = fs.createReadStream(path.join(this.cwd, file), {
      highWaterMark: chunkSize
    });

    for await (const chunk of readStream) yield chunk;
  }

实施失败(我尝试了不同的 createReadStream 模拟但没有成功):

describe('Work Dir Utils', () => {
  jest.mock('fs');

  let workDirUtils: WorkDirUtils;

  beforeEach(() => {
    (os.tmpdir as jest.Mock).mockReturnValue('/tmp');
    (fs.mkdtempSync as jest.Mock).mockReturnValue('/tmp/folder/pref-rand');
    (fs.createReadStream as jest.Mock).mockReturnValue({});
    workDirUtils = new WorkDirUtils();
    workDirUtils.createTempDir('pref-');
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should read chunks of a file using generator', async () => {
    for await (const chunk of workDirUtils.readChunks(
      path.join(__dirname, './fixtures/manifest.ts'),
      1024 * 1024 * 1024
    )) {
      expect(chunk).toBeInstanceOf(Buffer);
    }
  });
});

有什么建议吗?

其实很简单。最后,我不想撤销这个问题。也许对其他人有用。

jest.mock('fs');
jest.mock('tar');
jest.mock('os');
let workDirUtils: WorkDirUtils;

describe('Work Dir Utils', () => {
  beforeEach(() => {
    (os.tmpdir as jest.Mock).mockReturnValue('/tmp');
    (fs.mkdtempSync as jest.Mock).mockReturnValue('/tmp/folder/pref-rand');
    (fs.existsSync as jest.Mock).mockReturnValue(true);
    (fs.createReadStream as jest.Mock).mockReturnValue(Readable.from([path.join(__dirname, './fixtures/manifest.ts')]));
    workDirUtils = new WorkDirUtils();
    workDirUtils.createTempDir('pref-');
  });

  afterEach(() => {
    jest.clearAllMocks();
  });

  it('should generator function throw an error', async () => {
    const workdirUtilsMock = new WorkDirUtils();

    const generator = workdirUtilsMock.readChunks('file-path', 5000);

    expect(generator.next).rejects.toThrow('Working directory is not set!');
  });

  it('should read chunks of a file using generator', async () => {
    const generator = workDirUtils.readChunks(path.join(__dirname, './fixtures/manifest.ts'), 1024 * 1024 * 1024);

    const response = await generator.next();

    expect(response).toBeInstanceOf(Object);
    expect(response.value).toEqual(path.join(__dirname, './fixtures/manifest.ts'));
  });
});