jestjs - Jest 方法 done() 未定义

标签 jestjs

我开始使用 jest,现在我需要测试回调。
要知道何时调用回调,应根据文档使用 done():https://jestjs.io/docs/en/asynchronous.html

但是, done() 未被识别为未定义,因此抛出此错误:

Test suite failed to run

    TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
   pathToErrorFile:line - error TS2304: Cannot find name 'done'.

    63       done();
             ~~~~

//code to reproduce:
test('test', ()=>{
   fkt(param, ()=>{
      done();   
   }); 
}); 

我已经用 node 和 angular 设置了 jest 并且在这两个项目中都不存在这个功能。
所以我想知道的是,这个功能甚至来自哪里以及我如何对其进行故障排除。
请注意,其他所有内容(测试、描述等)都可以正常工作 done() 作为异常(exception)。

最佳答案

done未定义为全局变量。你把它传递给测试函数。

test('test', done => {
   fkt(param, () => {
      done();   
   }); 
});
请注意,如果您指定 done参数,如果 done,jest 将检测到它并且超时测试失败。测试完成后不会调用函数。

If done() is never called, the test will fail (with timeout error), which is what you want to happen.


然后,您必须调用done即使测试失败 - 否则您将不会看到错误。

If we want to see in the test log why it failed, we have to wrap expect in a try block and pass the error in the catch block to done. Otherwise, we end up with an opaque timeout error that doesn't show what value was received by expect(data).


Jest - Testing Asynchronous Code

关于jestjs - Jest 方法 done() 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57873442/

相关文章:

javascript - [React-Native][Jest]SyntaxError : Unexpected token import

reactjs - 如何测试渲染的 React 组件的 HTML?

Typescript 测试绝对导入检查问题

reactjs - 使用 Jest 和 Enzyme 测试 React 组件 : where to test whether component props were given

javascript - React (Native) 设置 Jest 来测试 Context 组件

reactjs - 如何使用 React 测试库模拟 Stencil Web 组件?

javascript - 在 Jest 中模拟导入

javascript - React.js 组件有通用的测试标准吗?

javascript - 是否可以使用 Jest 测试旧的非模块 JavaScript?

javascript - 使用 Typescript 在 Jest 中模拟类时引发 "Missing semicolon"错误