Using the jest framework, how can I verify that my async function throws something other than an Error?
In my examples below, the first one works as expected, as the function being tested throws an Error. The second example, where the function throws a string, doesnt work - jest doesnt verify that the function throws.
// Works as expected
test('verify error thrown', async () => {
const expected = new Error('actual-error');
const fn = async () => { throw expected; };
await expect(fn()).rejects.toThrow(expected);
});
// Fails with: Received function did not throw
test('verify non-error thrown', async () => {
const expected = 'non-error';
const fn = async () => { throw expected; };
await expect(fn()).rejects.toThrow(expected);
});
I don't think you need 'rejects' in either case. According to the docs it's not clear if the toThrow method expects results to be derived from Error. There is a regex form which might validate against a string.
rejects says that it unwraps the rejection so it can be matched, and that might give you the error message string from Error, or a string if the result was a string.
Dave's point was absolutely right; using rejects.toThrow was not the right way to go here.
Instead, I'm managed to verify the expected behaviour by simply catching the error and verifying it's value.
test('verify non-error thrown', async () => {
const expected = 'non-error';
const fn = async () => { throw expected; };
await fn().catch(error => expect(error).toStrictEqual(expected));
expect.assertions(1);
});
Note that expect.assertions(1) is important here. Without this, if the code being tested was updated to not throw, the test would still pass.