DEV Community

Discussion on: The only 3 steps you need to mock an API call in Jest

Collapse
 
jikuja profile image
Janne Kujanpää

Throwing an exception is one solution butcode under test might catch exceptions but I have not found any nice way to do something simple like fail().

Looks like there has been plans for fail(<message>) in jest-extended(1) but is it still unimplemented.

(1) npmjs.com/package/jest-extended#fa...

Looks like:

const throwUnmockedError = () => {
  expect(0).toEqual(1)
};

does the trick but is not really pretty and I'm sure that there are use cases when that approach just will not work.

Thread Thread
 
zaklaughton profile image
Zak Laughton

Oh you're right! There's not a great way to fail a test from an imported module when the tested code is in a try/catch. I found some suggestions in this Github issue thread about using fail() or done.fail(), but I was unable to get this to fail the test from the imported module.

Best alternative I could think of would be to throw a console.warn() message so at least there's an obvious indication in the terminal of the missing mock. Otherwise, I'd imagine you'd have to build some sort of custom global Jest rule that fails when it hits an unmocked end point. This blog also looked like it might have some solutions, but I didn't have time to test them: Jest explicitly or arbitrarily force fail() a test.

I'm very curious about this. Let me know if you find any better solutions!