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
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' });
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With