繁体   English   中英

开玩笑 - 断言异步 function 抛出测试失败

[英]Jest - assert async function throws test fails

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

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

活生生的例子

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

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

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

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

这虽然有效:

describe('foo', () => {
  it('should log and rethrow', async () => {
    await expect(foo()).rejects.toEqual('error')
  });
});

当我不想使用toEqualtoBe (就像其他正确答案一样)时,我会使用此代码。 相反,我使用toBeTruthy

async foo() {
  throw "String error";
}

describe('foo', () => {
  it('should throw a statement', async () => {
    await expect(foo()).rejects.toBeTruthy();
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM