How to test the type of a thrown exception in Jest
In Jest you have to pass a function into expect(function).toThrow(<blank or type of error>)
.
Example:
test("Test description", () => { const t = () => { throw new TypeError(); }; expect(t).toThrow(TypeError);});
Or if you also want to check for error message:
test("Test description", () => { const t = () => { throw new TypeError("UNKNOWN ERROR"); }; expect(t).toThrow(TypeError); expect(t).toThrow("UNKNOWN ERROR");});
If you need to test an existing function whether it throws with a set of arguments, you have to wrap it inside an anonymous function in expect()
.
Example:
test("Test description", () => { expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);});
It is a little bit weird, but it works and IMHO is good readable:
it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => { try { throwError(); // Fail test if above expression doesn't throw anything. expect(true).toBe(false); } catch (e) { expect(e.message).toBe("UNKNOWN ERROR"); }});
The Catch
block catches your exception, and then you can test on your raised Error
. Strange expect(true).toBe(false);
is needed to fail your test if the expected Error
will be not thrown. Otherwise, this line is never reachable (Error
should be raised before them).
@Kenny Body suggested a better solution which improve a code quality if you use expect.assertions()
:
it('should throw Error with message \'UNKNOWN ERROR\' when no parameters were passed', () => { expect.assertions(1); try { throwError(); } catch (e) { expect(e.message).toBe("UNKNOWN ERROR"); }});
See the original answer with more explanations: How to test the type of a thrown exception in Jest
I use a slightly more concise version:
expect(() => { // Code block that should throw error}).toThrow(TypeError) // Or .toThrow('expectedErrorMessage')