想要测试以下模块
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.
参考?在一个try-catch(err)
块中包裹expect(theFunctionFail()).rejects
不能避免我认为值得修复的警告。
为什么测试不会失败?/如何让测试失败?如果我的测试发现了严重的缺陷,那它不应该成功。
我正在使用Typescript和Jest 24.7.1与react-scripts
。
.catch
的promise,或者任何在try/catch
之外的await
。 - helloitsjoereturn
是至关重要的 - 这告诉 jest 在确定测试结果之前等待 promise 解析或拒绝。 - charlieb