Jest - 断言异步函数抛出测试失败

Dan*_*iel 5 javascript unit-testing reactjs jestjs

得到以下失败的测试用例,我不知道为什么:

foo.js

async function throws() {
  throw 'error';
}

async function foo() {
  try {
    await throws();
  } catch(e) {
    console.error(e);
    throw e;
  }
}
Run Code Online (Sandbox Code Playgroud)

测试.js

const foo = require('./foo');

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toThrow();
  });
});
Run Code Online (Sandbox Code Playgroud)

我希望 foo 抛出但由于某种原因它只是解决并且测试失败:

FAILED foo › should log and rethrow - Received function did not throw

活生生的例子

可能缺少异步等待抛出行为的一些基本细节。

小智 5

我认为你需要的是检查被拒绝的错误

const foo = require('./foo');
describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toEqual('error');
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 您还可以将代码调整为类似并且应该可以工作: `async function throws() { throw new Error('error'); }` (2认同)