【发布时间】:2022-01-11 15:43:40
【问题描述】:
我想为生成器函数编写单元测试,但我无法传递正确模拟的读取流 (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);
}
});
});
有什么建议吗?
【问题讨论】:
标签: javascript node.js testing stream mocking