Jest Failing With Unhelpful Error Message When Throwing New Error
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:
Let Jest catch it, using the built-in
toThrowexpectation 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
myFunctionin a function, to defer execution so that Jest can handle the error (otherwise the error is thrown beforeexpectcan be called and you're back in the same position).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() } })Without
expect.assertions, if a future change means that the call tolibrary.myFunctiondoes 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"