this trivial class is just an example ...
class SomeClass{
getTemplateName() {
throw new Error('foo');
}
}
... to try to test that some code throw an exception
describe('dome class', () => {
test('contains a method that will throw an exception', () => {
var sc = new SomeClass();
expect(sc.getTemplateName()).toThrow(new Error('foo'));
});
});
but is not working. What I am making wrong?
In Jest, when you test for a case where an error should be thrown, within your expect() wrapping of the function under testing you need to provide one additional arrow function wrapping in order for it to work. I.e.
Wrong (but most people's logical approach):
expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);
Right:
expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);
It's very strange but should make the testing run successfully.
Jest docs say:
If you want to test that a specific error gets thrown, you can provide an argument to toThrow. The argument can be a string for the error message, a class for the error, or a regex that should match the error.
So you should code it like this:
expect(sc.getTemplateName).toThrow('foo');
Or:
expect(sc.getTemplateName).toThrow(Error);
UPDATE: corrected expect
argument.
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