语境
我正在尝试使用Jest(24.9)编写一个测试用例,该用例具有异步回调函数,并且在运行时将成功。我写的测试用例似乎应该可以工作,但是失败了,我不清楚为什么。
测试用例
这是测试用例。它应该等待大约100毫秒,然后成功。
test("async test case", async () => {
await (new Promise((resolve) => {
setTimeout(() => {expect(true).toBe(true)}, 100);
}));
}, 10000);
错误信息
当我运行测试用例时,它失败并显示以下错误消息:
: Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.
Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.Error:
at new Spec (C:\Users\<username>\WebstormProjects\jest-async-test\node_modules\jest-jasmine2\build\jasmine\Spec.js:116:22)
at new Spec (C:\Users\<username>\WebstormProjects\jest-async-test\node_modules\jest-jasmine2\build\setup_jest_globals.js:80:9)
at new JBPatchedSpec (C:\Program Files\JetBrains\WebStorm 2019.2.1\plugins\JavaScriptLanguage\helpers\jest-intellij\lib\jest-intellij-jasmine-reporter.js:94:7)
at specFactory (C:\Users\<username>\WebstormProjects\jest-async-test\node_modules\jest-jasmine2\build\jasmine\Env.js:575:24)
at Env.it (C:\Users\<username>\WebstormProjects\jest-async-test\node_modules\jest-jasmine2\build\jasmine\Env.js:644:24) at Env.it (C:\Users\<username>\WebstormProjects\jest-async-test\node_modules\jest-jasmine2\build\jasmineAsyncInstall.js:132:23)
at it (C:\Users\<username>\WebstormProjects\jest-async-test\node_modules\jest-jasmine2\build\jasmine\jasmineLight.js:93:21)
at Object.<anonymous> (C:\Users\<username>\WebstormProjects\jest-async-test\async.test.js:2:25)
...
问题
为什么此测试用例失败?
用异步回调将成功的简单测试用例的例子将是什么?
此测试用例中有多个回调。错误消息指的是哪一个?
最佳答案
这是一个简单的错误。正如@Emissary指出的那样,Promise从未得到解决。通过的测试用例版本如下所示:
test("async test case", async () => {
await (new Promise((resolve) => {
setTimeout(() => {expect(true).toBe(true)}, 100);
resolve();
}));
}, 10000);
关于javascript - 为什么这个带有简单异步回调的测试用例(Jest)失败了?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58123450/