Question: How to test what kind of error an async function throws and how to apply matchers to the rejected value?
Answer: You need to await
the expect
call and then inspect the rejects
property of the returned Jest object.
async function doSomethingAsync(value?: string) {
if (!value) throw new MyFancyError('Some error text');
return value;
}
const error = await expect(doSomethingAsync()).rejects;
It's still a Promise so you need to await the matchers, too.
await error.toBeInstanceOf(MyFancyError);
await error.toMatch(/Some error text/i);
await error.toHaveProperty('foo', 'bar');