得到了以下失败的测试用例,我不确定为什么:
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
可能缺少异步等待抛出行为的一些基本细节。
答案 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)
当我不想使用toEqual
或toBe
时(例如其他正确答案),我将使用此代码。相反,我使用toBeTruthy
。
async foo() {
throw "String error";
}
describe('foo', () => {
it('should throw a statement', async () => {
await expect(foo()).rejects.toBeTruthy();
});
});