Skip to content
Advertisement

asserting against thrown error objects in jest

I have a function which throws an object, how can I assert that the correct object is thrown in jest?

it('should throw', () => {

  const errorObj = {
    myError: {
      name: 'myError',
      desc: 'myDescription'
    }
  };

  const fn = () => {
    throw errorObj;
  }

  expect(() => fn()).toThrowError(errorObj);
});

https://repl.it/repls/FrayedViolentBoa

Advertisement

Answer

If you are looking to test the contents of a custom error (which I think is what you are trying to do). You could catch the error then perform an assertion afterwards.

it('should throw', () => {
 let thrownError;

 try {
   fn();
 }
 catch(error) {
  thrownError = error;
 }

 expect(thrownError).toEqual(expectedErrorObj);
});

As Dez has suggested the toThrowError function will not work if you do not throw an instance of a javascript Error object. However, you could create your custom error by decorating an instance of an error object.

e.g.

let myError = new Error('some message');
myError.data = { name: 'myError',
                 desc: 'myDescription' };
throw myError;

Then once you had caught the error in your test you could test the custom contents of the error.

expect(thrownError.data).toEqual({ name: 'myError',
                                   desc: 'myDescription' });
Advertisement