Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 339
Daniel Billingham Avatar asked Feb 09 '18 13:02

Daniel Billingham


2 Answers

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' });
like image 80
Duncan Alexander Avatar answered Oct 06 '22 00:10

Duncan Alexander


It's known issue in jest, see https://github.com/facebook/jest/issues/8140

Meanwhile, here is my workaround - https://github.com/DanielHreben/jest-matcher-specific-error

like image 33
Daniel Avatar answered Oct 05 '22 23:10

Daniel