10

Writing Jest Tests That Expects An Error To Be Thrown

Wednesday, November 11, 2020

Jest has some tools for expecting an error to be thrown, but it's a bit confusing how to call it.

Official Docs.

The confusing part is if you simply call the function you expect to throw, the error will actually throw on the call stack, causing your test to fail.

The Jest API actually expects you to wrap the function you wish to call in another function when using toThrowError().

Code Examples

This will pass

function assertString(x: string): asserts x is string {
  if (typeof x !== 'string) {
    throw new Error('assertString failed.');
  } 
}

describe('assertString', () => {
  test('it should throw if called with a non-string', () => {
    expect(() => assertString(42)).toThrowError('assertString failed');
  });
})

This will fail

function assertString(x: string): asserts x is string {
  if (typeof x !== 'string) {
    throw new Error('assertString failed.');
  } 
}

describe('assertString', () => {
  test('it should throw if called with a non-string', () => {
    expect(assertString(42)).toThrowError('assertString failed');
  });
})
Zack DeRose

Discussions are healthy ❤️