开玩笑-断言异步函数引发测试失败

时间:2019-11-15 09:30:58

标签: javascript reactjs unit-testing jestjs

得到了以下失败的测试用例,我不确定为什么:

foo.js

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

async function foo() {
  try {
    await throws();
  } catch(e) {
    console.error(e);
    throw e;
  }
}

test.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

Live example

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

3 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

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

这可以:

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

答案 2 :(得分:0)

当我不想使用toEqualtoBe时(例如其他正确答案),我将使用此代码。相反,我使用toBeTruthy

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

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