为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

catspeake 2022-01-01 20:08:15
得到以下失败的测试用例,我不知道为什么:foo.jsasync function throws() {  throw 'error';}async function foo() {  try {    await throws();  } catch(e) {    console.error(e);    throw e;  }}测试.jsconst 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可能缺少异步等待抛出行为的一些基本细节。
查看完整描述

3 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

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


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

describe('foo', () => {

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

    await expect(foo()).rejects.toEqual('error');

  });

});


查看完整回答
反对 回复 2022-01-01
?
PIPIONE

TA贡献1829条经验 获得超9个赞

似乎这是一个已知的错误:https : //github.com/facebook/jest/issues/1700


这虽然有效:


describe('foo', () => {

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

    await expect(foo()).rejects.toEqual('error')

  });

});


查看完整回答
反对 回复 2022-01-01
?
慕神8447489

TA贡献1780条经验 获得超1个赞

当我不想使用toEqualor toBe(如其他正确答案)时,我会使用此代码。相反,我使用toBeTruthy.


async foo() {

  throw "String error";

}


describe('foo', () => {

  it('should throw a statement', async () => {

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

  });

});


查看完整回答
反对 回复 2022-01-01
  • 3 回答
  • 0 关注
  • 460 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号