我有一个方法
private processWriteNextChunk(filePath: string): void {
const nextChunk = this.data.get(filePath)?.shift();
if (!nextChunk) return;
appendFile(filePath, nextChunk.buffer, () => {
nextChunk?.last ? this.data.delete(filePath) : this.emitWriteNextChunk(filePath);
});
}我正在测试它,就像
it('should call appendFile when chunk array is not empty and delete data pair if it was last chunk',() => {
let appendFileCallback;
const appendFileSpy = jest.spyOn(fs, 'appendFile').mockImplementation((path, data, callback) => {
appendFileCallback = callback;
});
const data: IBufferChunk = { ...MOCK_DATA, last: true };
service.data.set(MOCK_PATH, [data]);
service.processWriteNextChunk(MOCK_PATH);
expect(appendFileSpy).toHaveBeenCalledWith(MOCK_PATH, data.buffer, appendFileCallback);
expect(service.data.size).toBe(0);
});测试失败,错误为

这是因为this.data.delete(filePath)没有时间工作,我如何解决这个问题?
发布于 2021-01-14 19:05:22
如果我理解正确的话,processWriteNextChunk代表一个异步操作。
因此,如果您将函数标记为async,并返回一个promise
private async processWriteNextChunk(filePath: string): Promise<YOUR_TYPE> {
//...
return appendFile(...)
}然后,您可以在jest it中使用await
it('should call appendFile when chunk array is not empty and call emitWriteNextChunk if it wasn\'t last chunk', async () => {
//...
await service.processWriteNextChunk(MOCK_PATH);
});发布于 2021-01-14 19:44:11
我的问题是mockImplementation函数改变了函数的工作方式,所以我的回调函数还没有被调用,所以我只是让它像这样
const appendFileSpy = jest
.spyOn(fs, 'appendFile')
.mockImplementation((path, data, callback) => {
callback(null);
appendFileCallback = callback;
});它工作得很好
https://stackoverflow.com/questions/65717435
复制相似问题