ant测试以下模块index.ts
async function theFunctionFail() {
return await fail();
}
async function theFunctionSucceed() {
return await succeed();
}
async function fail() {
throw new Error();
}
async function succeed() {
return "a";
}
export { theFunctionFail, theFunctionSucceed };
使用测试index.test.ts
import { theFunctionFail, theFunctionSucceed } from "../index";
it('theFunctionFail', () => {
expect(theFunctionFail()).rejects;
});
输出中的UnhandledPromiseRejectionWarning
是什么
(node:10515) UnhandledPromiseRejectionWarning: Error
(node:10515) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:10515) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
PASS src/__tests__/index.test.ts
✓ theFunctionFail (6ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.806s
Ran all test suites.
指的是?将expect(theFunctionFail()).rejects
包装在try-catch(err)
块中并不能避免我认为值得修复的警告。
为什么测试不会失败?/如何使测试失败?如果我的测试发现了严重的缺陷,那么就我的理解而言,它不会成功。
我在react-scripts
中使用Typescript和Jest 24.7.1。
答案 0 :(得分:1)
此警告表示以下事实:测试中发生了未处理的错误。真正的问题是您的测试没有测试任何东西-有expect
没有匹配器。这应该是这样:
return expect(theFunctionFail()).rejects.toEqual(new Error());
请参阅.rejects
的Jest文档:https://jestjs.io/docs/en/tutorial-async#rejects
注意:也可以使用try/catch
,但是您必须像这样使用await
:
it('theFunctionFail', async () => {
expect.assertions(1);
try {
await theFunctionFail();
} catch (err) {
expect(err).toEqual(new Error());
}
});
或者返回异步函数并捕获错误(确保您返回了函数):
it('theFunctionFail', () => {
expect.assertions(1);
return theFunctionFail().catch(err => {
expect(err).toEqual(new Error());
});
});
expect.assertions(number)
是一种确保在测试异步行为时调用所有expect
的好方法。
此外,如果您添加错误消息,例如new Error('oh no!')
,您将确定自己正在捕获正确的错误,并且调试起来会更容易。
答案 1 :(得分:0)
在控制台中不会产生UnhandledPromiseRejectionWarning的最干净的解决方案是使用jest的expect.toThrow()函数。
import { theFunctionFail, theFunctionSucceed } from "../index";
it('theFunctionFail', () => {
expect(theFunctionFail()).rejects.toThrow();
});
同样,您可以尝试匹配特定的错误。例如。如果:
async function fail() {
throw new Error('Something failed');
}
然后,您将使用以下命令进行测试:
it('theFunctionFail', () => {
expect(theFunctionFail()).rejects.toThrow(Error('Something failed'));
});