玩笑测试中 UnhandledPromiseRejectionWarning 的含义是什么?

Kar*_*ter 10 javascript unit-testing promise typescript jestjs

蚂蚁来测试以下模块 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 };
Run Code Online (Sandbox Code Playgroud)

使用测试 index.test.ts

import { theFunctionFail, theFunctionSucceed } from "../index";

it('theFunctionFail', () => {
  expect(theFunctionFail()).rejects;
});
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

参考?包装expect(theFunctionFail()).rejects在一个try-catch(err)块中并不能避免我认为值得修复的警告。

为什么测试不失败?/我怎样才能让测试失败?如果我的测试发现了一个严重的缺陷,在我的理解中它应该不会成功。

我正在将 Typescript 和 Jest 24.7.1 与react-scripts.

hel*_*joe 8

This warning refers to the fact that an error is happening in the test that isn't being handled. The real problem is that your test isn't testing anything - there's an expect without a matcher. Here's what it should be:

return expect(theFunctionFail()).rejects.toEqual(new Error());
Run Code Online (Sandbox Code Playgroud)

See the Jest docs for .rejects: https://jestjs.io/docs/en/tutorial-async#rejects

Note: It's also possible to use try/catch, but you have to either await like this:

it('theFunctionFail', async () => {
  expect.assertions(1);
  try {
    await theFunctionFail();
  } catch (err) {
    expect(err).toEqual(new Error());
  }
});
Run Code Online (Sandbox Code Playgroud)

Or return the async function and catch the error (make sure you return the function):

it('theFunctionFail', () => {
  expect.assertions(1);
  return theFunctionFail().catch(err => {
    expect(err).toEqual(new Error());
  });
});
Run Code Online (Sandbox Code Playgroud)

expect.assertions(number) is a good way to make sure all of your expects are being called when testing asynchronous behavior.

此外,如果您添加错误消息,例如new Error('oh no!'),您将确定您正在捕获正确的错误,并使调试更容易一些。