首页 > 解决方案 > 异步笑话断言没有失败测试,​​但断言错误打印在测试输出中

问题描述

我有一个返回承诺的提供者对象。我正在尝试为此提供程序对象创建开玩笑的单元测试。

这是一个示例测试:

  it('Should return repos for a known account', (done) => {
    expect.assertions(1);
    expect(apiProvider.ReposForUser('joon').then((data) => data.length)).resolves.toBeGreaterThan(0).then(done());
  });

我现在只是在提供程序类中用一个空白数组来解决承诺(即我希望测试失败):

export class GithubAPIProvider implements IGithubDataProvider {
  public ReposForUser(githubUser: string): Promise<GithubRepoData[]> {
    return new Promise<GithubRepoData[]>((resolve, reject) => {
      resolve([]);    
    });
  }  
}

当我运行我的 jest 脚本时,我在输出文本中看到一个失败的 promise 错误,但测试显示已通过: 在此处输入图像描述

我在测试中使用了 done 回调,为什么 jest 不等待回调?

标签: typescriptjestjs

解决方案


弄清楚问题是什么。我在 then 方法中调用 done 函数,而不是传递对 done 方法的引用。

代码现在看起来像这样:[“done”而不是“done()”]:

it('Should return repos for a known account', (done) => {
    expect.assertions(1);
    expect(apiProvider.ReposForUser('joon').then((data) => data.length)).resolves.toBeGreaterThan(0).then(done);
  });

推荐阅读