Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest: test that exception will be thrown isnt working

Tags:

node.js

jestjs

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?

like image 794
sensorario Avatar asked Feb 28 '18 10:02

sensorario


2 Answers

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.

like image 55
Adrian Avatar answered Oct 07 '22 18:10

Adrian


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.

like image 35
Miguel Calderón Avatar answered Oct 07 '22 18:10

Miguel Calderón