首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何等待appendFile work Jest回调

如何等待appendFile work Jest回调
EN

Stack Overflow用户
提问于 2021-01-14 18:39:53
回答 2查看 61关注 0票数 0

我有一个方法

代码语言:javascript
复制
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);
    });
  }

我正在测试它,就像

代码语言:javascript
复制
  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)没有时间工作,我如何解决这个问题?

EN

回答 2

Stack Overflow用户

发布于 2021-01-14 19:05:22

如果我理解正确的话,processWriteNextChunk代表一个异步操作。

因此,如果您将函数标记为async,并返回一个promise

代码语言:javascript
复制
 private async processWriteNextChunk(filePath: string): Promise<YOUR_TYPE> { 
    //...
    return appendFile(...)
 }

然后,您可以在jest it中使用await

代码语言:javascript
复制
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);
});
票数 0
EN

Stack Overflow用户

发布于 2021-01-14 19:44:11

我的问题是mockImplementation函数改变了函数的工作方式,所以我的回调函数还没有被调用,所以我只是让它像这样

代码语言:javascript
复制
const appendFileSpy = jest
      .spyOn(fs, 'appendFile')
      .mockImplementation((path, data, callback) => {
        callback(null);
        appendFileCallback = callback;
      });

它工作得很好

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65717435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档