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

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


foo.js


async function throws() {

  throw 'error';

}


async function foo() {

  try {

    await throws();

  } catch(e) {

    console.error(e);

    throw e;

  }

}

测试.js


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


describe('foo', () => {

  it('should log and rethrow', async () => {

    await expect(foo()).rejects.toThrow();

  });

});

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


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

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


catspeake
浏览 461回答 3
3回答

尚方宝剑之说

我认为你需要的是检查被拒绝的错误const foo = require('./foo');describe('foo', () => {  it('should log and rethrow', async () => {    await expect(foo()).rejects.toEqual('error');  });});

PIPIONE

似乎这是一个已知的错误:https : //github.com/facebook/jest/issues/1700这虽然有效:describe('foo', () => {  it('should log and rethrow', async () => {    await expect(foo()).rejects.toEqual('error')  });});

慕神8447489

当我不想使用toEqualor toBe(如其他正确答案)时,我会使用此代码。相反,我使用toBeTruthy.async foo() {  throw "String error";}describe('foo', () => {  it('should throw a statement', async () => {    await expect(foo()).rejects.toBeTruthy();  });});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript