jest-extended
jest-extended copied to clipboard
Feature Request: expect.toThrow with callback
Hey team, I raised https://github.com/facebook/jest/issues/7958 on the main Jest repo and the team suggested raising it here.
🚀 Feature Proposal
I think it would be useful to have a callback for the expect.toThrow function that receives the error that was thrown. Then I can make more assertions on the error in the callback. Quite often the error object has other information on them to verify, other than the message or name.
Motivation
At the moment I have to write such a test case like this:
test("Should throw an error", () => {
try {
somethingThatThrowsWithArgs(1);
fail("Did not throw");
} catch (e) {
expect(e.message).toEqual("Something");
expect(e.statusCode).toEqual(500);
}
});
Or like this (thanks for the tip @mattphillips ):
test('Should throw an error', () => {
const blowsUp = () => {
throw { message: 'Something', statusCode: 500 };
};
expect(blowsUp).toThrow(expect.objectContaining({
message: 'Something',
statusCode: 500
}));
});
Example
But it could be done like this to allow more complicated assertions on the error using all the other great expect
methods:
test("Should throw an error", () => {
expect(() => {
somethingThatThrowsWithArgs(1);
}).toThrow(error => {
expect(e.message).toEqual("Something");
expect(e.statusCode).toEqual(500);
});
});
Happy to hear feedback on this, if there is another way to achieve what I want, or just to find out it's a bad idea 😄