DEV Community

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

Collapse
 
zaklaughton profile image
Zak Laughton

Hi Florian!

For this, I'd recommend abstracting out the API call into a separate module. This gives you a single place to test the authentication, and leaves the rest of your tests cleaner and easier to maintain.

For the example in the article, this would mean having an apiProxy.js module that we send the request to instead of axios. The proxy module would handle fetching and authentication, and in the test, we'd be mocking apiProxy instead of axios.

If you want to test the authentication in apiProxy.js, this is probably one of the few instances where you would actually want to make a network call to ensure the authentication is happening as expected at the end point. This can get complex based on exactly how the authentication is taking place and how your application is structured. But essentially, you'll want to use network requests to mimic how an actual logon takes place. In the case of JWT, you can make a login network request, then save the token in a variable and send it in the header for the rest of your authentication tests.

Collapse
 
flrnd profile image
Florian Rand

I think I get it! Thanks for the detailed explanation! I have a middleware that checks the tokens, so I think I'm closer to the solution than I thought I was. This saved me a lot of try/error! Cheers! And again, thanks!