Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 36077  / 6 Years ago, fri, february 9, 2018, 12:00:00

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


More From » reactjs

 Answers
62

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

[#55209] Wednesday, February 7, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aidengiancarlop

Total Points: 234
Total Questions: 115
Total Answers: 94

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
;