Skip to content Skip to sidebar Skip to footer

Jest Failing With Unhelpful Error Message When Throwing New Error

I'm calling this function in my code and throwing an error: myFunction(message) { if (!message) { throw new Error('No Message') } } and the test: it.only('should t

Solution 1:

Your test is crashing, rather than failing, because the error thrown by myFunction is never caught. There are two broad solutions to this:

  1. Let Jest catch it, using the built-in toThrow expectation for errors:

    it.only('should throw error if no message', () => {
        expect(() => library.myFunction()).toThrow()
        expect(global.opener.postMessage).not.toHaveBeenCalled()
    })
    

    Note that in this case you need to wrap the call to myFunction in a function, to defer execution so that Jest can handle the error (otherwise the error is thrown before expect can be called and you're back in the same position).

  2. Catch it yourself, using try/catch, and explicitly ensure that one expectation is reached during the test:

    it.only('should throw error if no message', () => {
        expect.assertions(1)
        try {
            library.myFunction()
        catch (err) {
            expect(global.opener.postMessage).not.toHaveBeenCalled()
        }
    })
    

    Withoutexpect.assertions, if a future change means that the call to library.myFunction does not throw an error, then no expectation is ever reached inside the test and it silently passes. It's important to ensure that either all logical paths through your test have expectations, or you explicitly check the expected number are reached.

Post a Comment for "Jest Failing With Unhelpful Error Message When Throwing New Error"