How can I make a jest test fail on any error thrown?
I have tried around a bit, but haven't nailed the syntax yet.
test('getArcId => Error', async () => {
await expect(client.getArcId('skynet')).rejects.toThrow();
});
I get the error message
getArcId › getArcId => Error
expect(received).rejects.toThrow()
Received function did not throw
However the following test passes, so the function I intend to test does throw (at least to the best of my understanding of what throw means):
test('getArcId => Error', async () => {
await client.getArcId('skynet').catch(e =>
expect(e.message).toBe('Command failure')
);
});
I couldn't get toThrow()
to work, but doing the tests like so did work;
it('throws on connection error', async () => {
expect.assertions(1);
await expect(nc.exec({ logger: true }))
.rejects.toEqual(Error('No command provided to proxy.'));
});
If I reject just a message;
.rejects.toEqual('some message');
For Jest exception handling to work as expected, pass it an anonymous function like:
test('getArcId => Error', async () => {
await expect(() => client.getArcId('skynet')).rejects.toThrow();
});
From the jest documentation
test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
Please note the anonymous function. Yeah, that got me a few times :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With