簡體   English   中英

單元測試異步生成器 function in Jest

[英]Unit test asynchronous generator function in Jest

我想為生成器 function 編寫單元測試,但我無法通過正確模擬的讀取 stream( ReadStream )object。

可測試 function:

  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 的不同 mocking 但沒有成功):

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'));
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM