Reputation: 6481
Got the following failing test case and i'm not sure why:
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();
});
});
I expect foo to throw but for some reason it just resolves and the test fails:
FAILED foo › should log and rethrow - Received function did not throw
Probably missing some basic detail of async await throw behavior.
Upvotes: 6
Views: 3531
Reputation: 1404
I use this code when I don't want to use toEqual
or toBe
(like the other correct answers). Instead, I use toBeTruthy
.
async foo() {
throw "String error";
}
describe('foo', () => {
it('should throw a statement', async () => {
await expect(foo()).rejects.toBeTruthy();
});
});
Upvotes: 1
Reputation: 106
I think what you need is to check the rejected error
const foo = require('./foo');
describe('foo', () => {
it('should log and rethrow', async () => {
await expect(foo()).rejects.toEqual('error');
});
});
Upvotes: 9
Reputation: 190
Seems like it's a known bug: https://github.com/facebook/jest/issues/1700
This works though:
describe('foo', () => {
it('should log and rethrow', async () => {
await expect(foo()).rejects.toEqual('error')
});
});
Upvotes: 2