Skip to content

Instantly share code, notes, and snippets.

@jukkatupamaki
Last active April 29, 2024 06:25
Show Gist options
  • Save jukkatupamaki/fbf2a1ea0bfe6ff7e3bbd8175ce092f6 to your computer and use it in GitHub Desktop.
Save jukkatupamaki/fbf2a1ea0bfe6ff7e3bbd8175ce092f6 to your computer and use it in GitHub Desktop.
Asserting async errors with Jest

Asserting async errors with Jest

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');

Docs: https://jestjs.io/docs/expect#rejects

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment