DEV Community

Cover image for The only 3 steps you need to mock an API call in Jest
Zak Laughton
Zak Laughton

Posted on • Edited on • Originally published at zaklaughton.dev

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

I recently found myself working in a Javascript codebase where I needed to implement new Jest tests. I knew very little at the time about writing tests, so I looked to Jest docs and existing patterns in the codebase to figure out best practices and how to do it. It was fairly straightforward, and I even found myself enjoying testing. But I could not for the life of me reliably mock an API call.

Dog with caption

The docs seemed clear, and the existing code appeared to have good patterns, but there were just so many ways to mock things. The existing tests used all sorts of mocking methods such as jest.genMockFromModule(), jest.spyOn(), and jest.mock(). Sometimes the mocks were inline, sometimes they were in variables, and sometimes they were imported and exported in magical ways from mysterious __mocks__ folders. I used these techniques interchangeably every time I got a burst of confidence in understanding, only to find myself stumbling over the different methods and their effects. I had no idea what I was doing.

The issue

The issue was that I was trying to learn how to run before I even knew how to walk. Jest has many powerful ways to mock functions and optimize those mocks, but they're all useless if you don't know how to make a simple mock in the first place. And while the Jest documentation provides a lot of great insight and techniques, I couldn't figure out where to start.

In this article, I hope to give you absolute basics to mock an API call so you can benefit from my 2020 hindsight (heh). If you're going crazy like I was because you can't figure out how to just make a simple damn mock, Start here…

(NOTE: The code below was written in Node.js, but the mocking concepts also apply to frontend Javascript and ES6 modules)

The unmocked code

We're going to be testing this getFirstAlbumTitle() function, which fetches an array of albums from an API and returns the title of the first album:



// index.js
const axios = require('axios');

async function getFirstAlbumTitle() {
  const response = await axios.get('https://jsonplaceholder.typicode.com/albums');
  return response.data[0].title;
}

module.exports = getFirstAlbumTitle;



Enter fullscreen mode Exit fullscreen mode

...and here's our initial mock-less test for this function, which verifies the function actually returns the title of the first album in the list:



// index.test.js
const getFirstAlbumTitle = require('./index');

it('returns the title of the first album', async () => {
  const title = await getFirstAlbumTitle();  // Run the function
  expect(title).toEqual('quidem molestiae enim');  // Make an assertion on the result
});


Enter fullscreen mode Exit fullscreen mode

The test above does its job, but the test actually makes a network request to an API when it runs. This opens the test up to all sorts of false negatives if the API isn't working exactly as expected (e.g. the list order changes, API is down, dev machine loses network connection, etc.). Not to mention, making these requests in a large number of tests can bring your test runs to a slow crawl.

But how can we change this? The API request is being made with axios as a part of getFirstAlbumTitle(). How in the world are we supposed to reach inside the function and change the behavior?

Mock it in 3 steps

Alright, here it is. This is the big secret that would have saved me mountains of time as I was wrestling with learning mocks. To mock an API call in a function, you just need to do these 3 steps:

1. Import the module you want to mock into your test file.
2. jest.mock() the module.
3. Use .mockResolvedValue(<mocked response>) to mock the response.

That's it!

Here's what our test looks like after doing this:



// index.test.js
const getFirstAlbumTitle = require('./index');
const axios = require('axios');

jest.mock('axios');

it('returns the title of the first album', async () => {
  axios.get.mockResolvedValue({
    data: [
      {
        userId: 1,
        id: 1,
        title: 'My First Album'
      },
      {
        userId: 1,
        id: 2,
        title: 'Album: The Sequel'
      }
    ]
  });

  const title = await getFirstAlbumTitle();
  expect(title).toEqual('My First Album');
});



Enter fullscreen mode Exit fullscreen mode

What's going on here?

Let's break this down. The most important part to understand here is the import and jest.mock():



const axios = require('axios');

jest.mock('axios');


Enter fullscreen mode Exit fullscreen mode

When you import a module into a test file, then call it in jest.mock(<module-name>), you have complete control over all functions from that module, even if they're called inside another imported function. Immediately after calling jest.mock('axios'), Jest replaces every function in the axios module with empty "mock" functions that essentially do nothing and return undefined:



const axios = require('axios');
jest.mock('axios')

// Does nothing, then returns undefined:
axios.get('https://www.google.com')

// Does nothing, then returns undefined:
axios.post('https://jsonplaceholder.typicode.com/albums', {
    id: 3,
    title: 'Album with a Vengeance'
})


Enter fullscreen mode Exit fullscreen mode

So now that you've eliminated the default behavior, you can replace it with your own...



  axios.get.mockResolvedValue({
    data: [
      {
        userId: 1,
        id: 1,
        title: 'My First Album'
      },
      {
        userId: 1,
        id: 2,
        title: 'Album: The Sequel'
      }
    ]
  });



Enter fullscreen mode Exit fullscreen mode

The mocked replacement functions that Jest inserted into axios happen to come with a whole bunch of cool superpower methods to control their behavior! The most important one here, for the purposes of a simple beginner mock, is .mockResolvedValue(). When you call this on a mocked method, anything you pass in will be the default return value when the mocked function is called for the remainder of the test. Simply put: you can make axios.get() return whatever you want! And it doesn't matter whether it's called directly in your test file or as a part of a function imported into your test – Jest will mock the function no matter where it's called!

Use this newfound power to give your functions exactly what they should expect from the API calls. Stop worrying about what the network requests return, and just focus on what YOUR code does once it gets the response!

If you want to play around with the examples, feel free to use this demo repository:

GitHub logo ZakLaughton / DEMO-simple-api-mocking-with-jest

A simple API mocking example with Jest.

Wrapping up

There you have it! This is the very basics of what you need to mock functions from another module: import the module, jest.mock() the module, then insert your own return values with .mockResolvedValue()!

I recommend starting here, using only these techniques as you start building out your first mocks for your network calls. Once you have a foundational understanding of what's going on here, you can slowly start adding the other robust mocking features included in Jest.

See also: Mocking Modules (Jest documentation).

EDIT: Also, be sure to clear your mocks between tests by running jest.resetAllMocks() after each test. This will help ensure your mocks won't interfere with future tests. (Thanks for pointing this out, @mjeffe!)


Where to go from here

Alright, you've learned the basics of mocking and successfully implemented the strategies above in several tests. You can import and mock resolved values for all your API calls like an old pro. What's next?

While the methods described above will cover most simple use cases, Jest has a lot of mocking functionality and methods to do some really powerful things. You can incrementally add some of the concepts below to super-charge your mocks:

  1. Check out the other mock function methods listed in the Jest docs: Mock Functions. You can use methods such as mockReturnedValue() to mock synchronous returns and mockResolvedValueOnce() to only return a value the first time it's called.
  2. Want to see how many times a mocked function is called, what it was called with, and what it returned? Check out the mock.calls and mock.results properties (also in the Mock Functions documentation)
  3. Do you have your own custom functions that make network requests? You can mock your own modules too after they're imported into the test file: jest.mock('./path/to/js/module/file')! Careful here though that you're only mocking what's necessary. Your tests should make sure your functions do what's expected with a given mock input, and it can be easy to end up writing tests that instead just confirm you passed in mocked data.
  4. Want a function to act as it was originally written, but still want to see how many times it was called? Check out jest.spyOn().
  5. Find yourself mocking the same function over and over in multiple tests? Give it default mock responses in __mocks__ folders using Manual Mocks!

I hope this saves others some of the wasted time and frustration I went through! If anything doesn't make sense here, please leave a comment and I'd be happy to try to answer any questions. Also, let me know if there's anything else that helped you have an "Aha!" moment while learning to mock!


_Did you find this this article useful? Feel free to subscribe to my articles below or [follow me on Twitter](https://twitter.com/ZakLaughton) for more developer tips and article announcements!_

Top comments (63)

Collapse
 
chiubaca profile image
Alex Chiu • Edited

Thanks for this, very useful. I'm having a bit of trouble with this though...
my mockResolvedResponse is being returned undefined and I have no idea why!

import axios from "axios";
import { Users } from "./api-call"

jest.mock('axios')

describe('axios tests with mocking', () => {
  test('should fetch posts', async () => {

    const fakeResp = [
      {
        "userId": 1,
        "id": 2,
        "title": "qui est esse",
        "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
      }]

    mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
    mockedAxios.get.mockResolvedValue(fakeResp)

    const axiosSpy = spyOn(mockedAxios, 'get')

    const result = await Users.all()

    expect(result).toEqual(fakeResp)  //❌Fails....
    expect(axiosSpy).toHaveBeenCalledTimes(1)  //✔Passes!

  });

});
Enter fullscreen mode Exit fullscreen mode

any ideas if I'm doing something silly?

Collapse
 
zaklaughton profile image
Zak Laughton • Edited

Sure! I'm not sure exactly what the root cause is, but I've got some troubleshooting steps to start.

My observations

jest.mock() vs jest.spyOn()

Looks like here you are using jest.mock() and jest.spyOn() here on the same function. Usually, these are used interchangeably, but not together. Both functions let you inspect how the function was called. The difference between the 2 is that jest.mock() completely blows away the original function being mocked, while jest.spyOn() keeps the original implementation so the function runs as it is was written. In most cases, I find I only need jest.mock(). (This article seems to do a good job diving into the comparison a bit more Understanding Jest mocks)

Here, it looks like you're spying on your mock, which is redundant, and might have unpredictable results. I'm not sure if that's the issue here, but it's a layer of complexity I'd take out. You should be able to check on the number of calls without the spy (see my suggestion in "What I'd do" below).

Mocking resolved and rejected values

Here, you're using mockedRejectedValue() and mockResolvedValue() on the same function:

mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
mockedAxios.get.mockResolvedValue(fakeResp)
Enter fullscreen mode Exit fullscreen mode

This is redundant because each one will completely overwrite the mocked implementation, so first you set it to reject (no matter what), then you set it to resolve no matter what. Since your expected output (mockResolvedValue(fakeResp)) comes second, the .mockRejectedValue('Network error: Something went wrong') has no impact here. It won't change the output, but I'd remove it just to reduce the complexity for troubleshooting.

mockRejectedValue() is typically only needed if you are explicitly testing an error state (See also: Jest docs for mockRejectedValue() and mockResolvedValue()).

What I'd do

With the notes above, I'd remove some of the redundant code, then if it's still not working, dig into how the mocked function is being called:

  1. Remove the spyOn()

    - const axiosSpy = spyOn(mockedAxios, 'get')
        [...]
    - expect(axiosSpy).toHaveBeenCalledTimes(1) 
    + expect(axios.get).toHaveBeenCalledTimes(1) 
    
  2. Remove the mockRejectedValue()

    - mockedAxios.get.mockRejectedValue('Network error: Something went wrong');
    
  3. If the issue still isn't resolved, you can dig into what axios.get is being called with and what it's returning:

    console.log("axios.get() called with>>>", axios.get.mock.calls[0]);
    console.log("axios.get() returns>>>", axios.get.mock.results[0]);
    

    This should show exactly how axios.get() is being called in Users.all() (see more details on this type of mock call inspection in the jest docs here: Mock Functions). You can also throw some console.logs in the actual Users.all() function, too, which will also output to the terminal during the test.

Here's an example of what that console.log output looks like when I add it to the sample code from this article:

code screenshot

I hope this helps!

Collapse
 
chiubaca profile image
Alex Chiu • Edited

Wooah thanks for such a detailed reply!

I forgot to mention one crucial piece of information. I'm trying to do this with TypeScript! ** plot-twist! **

This means I get errors when trying to use axios.get.mock. I think this why I started playing around with jest spies, as it a bit more of type friendly method of getting the assertion metadata out.

Thread Thread
 
zaklaughton profile image
Zak Laughton

Ah, got it! Yeah, how to type mock functions is not immediately clear. Try this:

(axios.get as jest.Mock).mockResolvedValue(fakeResp)
Enter fullscreen mode Exit fullscreen mode

That should at least pass type checking and give you the auto-complete in your editor for mock functions. This should be good enough to at least get it working. If I remember correctly though, it won't actually check the types on the resolved value, so fakeResp could be any type, even if it doesn't match the return type of Users.all(). You'll also have to add as jest.Mock everywhere you call axios.get

If you want stricter typing for this without needing to cast as jest.Mock each time, I've had a great experience with ts-jest. Looks like they've updated a lot since I used it last, so I can't give a syntax example, but you can check out their docs.

tl;dr: use (axios.get as jest.Mock) for generic mock function types, or use a tool like ts-jest for stricter types of that specific mock function.

Thread Thread
 
chiubaca profile image
Alex Chiu

Thank you so much! Was finally able to get the test passing! The trick of using (axios.get as jest.Mock) was the key to letting me debug this thoroughly.

Collapse
 
ramyac032001 profile image
c Ramya

can i except the data in the screen to bind in the front end like
expect(screen.getByText(''my first album')).toBeInTheDocument();
but i try this above line ,it should not work .give any soltuion for that?

Collapse
 
viktorhsn profile image
Victor H Nascimento • Edited

Hi Zak,

Thank you very much for your article, it helped me a lot.
I am having trouble replicating this with typescript, it complains when I try to set the mockResolvedValue into axios get.

test("it should return permission true", async() => {
axios.get.mockResolvedValue({ //type error here.
true
});

expect(await wrapper.obterPermissaoUsuario("token","COD_APLIC","LIMIT")).toBe(true);
Enter fullscreen mode Exit fullscreen mode

});

Collapse
 
zaklaughton profile image
Zak Laughton

Hi Victor! Glad the article helped!

Typescript isn't great at determining the types of mocked values, but there are some great libraries to help. Personally, I've had great success using the mocked method from ts-jest. See details and usage examples here: ts-jest/test-helpers

Collapse
 
antoyne7 profile image
Antoine Braillard

try (axios.get as jest.Mock).mockReturnValue({})

Collapse
 
jikuja profile image
Janne Kujanpää

Is it possible to make jest.mock(<module>) call to create function calls which emits fail instead of returning null?

If you use such a scheme you know that all the function calls into mocked module are covered by user defined mocks. Would it make any sense?

Collapse
 
zaklaughton profile image
Zak Laughton • Edited

I think I see what you're saying: Returning undefined in a mocked endpoint is ambiguous, and it would be nice to instead return an error that clearly says "This endpoint/mock is not defined". I hadn't thought about before. Great idea!

Doing some research, I can't find a built-in Jest method to automatically make all function calls in a module fail, but you can create a manual mock file that will return an error for all functions using .mockImplementation():

// __mocks__/axios.js
const axios = jest.genMockFromModule('axios');

const throwUnmockedError = () => {
  throw new Error(`This endpoint has been mocked, but hasn't been given a manual response`);
};

// Make all axios methods return the unmocked error
// List of axios methods taken from README at https://github.com/axios/axios
axios.post.mockImplementation(throwUnmockedError);
axios.request.mockImplementation(throwUnmockedError);
axios.get.mockImplementation(throwUnmockedError);
axios.delete.mockImplementation(throwUnmockedError);
axios.head.mockImplementation(throwUnmockedError);
axios.options.mockImplementation(throwUnmockedError);
axios.post.mockImplementation(throwUnmockedError);
axios.put.mockImplementation(throwUnmockedError);
axios.patch.mockImplementation(throwUnmockedError);

module.exports = axios;
Enter fullscreen mode Exit fullscreen mode

Then, when you try to call a mocked function without a user-defined mock, the error will look something like this:

Jest unmocked output error screenshot

I created a branch on the demo repository that uses this strategy: mock-with-failed-requests. If you clone the repo, switch to that branch, and run npm run test:mocked, you'll get the error in the screenshot above.

If you play around with it a bit, there might also be a way to more clearly show exactly which mocked function triggered the error. You could also create a function to map through all the methods, which would clean up the manual mock and automatically include any additional methods added in the future.

I hope this helps!

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!

Collapse
 
mjeffe profile image
Matt Jeffery • Edited

Zak,

Great article, but I think you're missing a critical 4th step - resetting the mocks.

I just came across your post. I sure wish I'd found it earlier. Even though I'm an experienced programmer, I went through the same confusing process you describe when learning how to test Javascript with Jest. However, I knew enough about testing to know I needed to reset mocks after each test. There are subtle differences between the various reset options, but I generally do something like jest.resetAllMocks(); in a beforeEach(). I think you should at least mention the need for resetting, else the second test you write may not behave as expected.

Collapse
 
zaklaughton profile image
Zak Laughton • Edited

Great call-out! This is actually a best practice I've been ignoring in some of my own tests ("SHAME!"). I'll make an addendum to this article soon to add this detail and credit you for it. Thanks!

EDIT: Added

Collapse
 
flrnd profile image
Florian Rand • Edited

Hey Zak, this is really great! I've been recently facing a similar problem, what would you think it's the best approach when the API also has some kind of auth system, like jwt for example? Right now, the API I'm talking about is tested with supertest and I'd like to switch to jest (with its mocks, because it's a pain sometimes run the tests), and this article is going to be super-helpfull! Thanks for writing and sharing this!

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!

Collapse
 
thodwris profile image
Theodoros Kokosioulis

Thanks for that! That's helpful. I've tried what you said but I'm having a hard time to integrate the ts-jest. Could you take a look at stackoverflow.com/questions/626040...

Collapse
 
zaklaughton profile image
Zak Laughton

Just posted an answer on that question. Hope it helps!

Collapse
 
diabl0269 profile image
Diabl0269

Hey Zak, I wanted to tell you that i open this account just to comment on your article.
I was trying to understand how to mock a function's return value and was looking for it for hours.
I must say that your explanation was short and sweet.
Thank you.

Collapse
 
zaklaughton profile image
Zak Laughton

Good to hear I'm not the only one who found this so difficult to figure out at first! 😁 Glad I could save you some time in the end!

Collapse
 
markskinsley profile image
Mark Skinsley

Hi Zak, this is a great article; thank you for breaking this down and explaining how testing works with API calls. Creating the mock is quite an unusual thing to get my head round!

I have a React site that does almost all its rendering based on the result of API calls. Normally I make an API call inside useEffect and render JSX based on whether data is returned. From my limited TDD knowledge... it seems test tests run on initial render, so I always receive the initial JSX, i.e. no results. Is there a way to simulate the API call and run tests on the JSX after a positive response from the API?

Collapse
 
zaklaughton profile image
Zak Laughton • Edited

Definitely! My first recommendation is to use React Testing Library on top of Jest. React Testing Library is quickly becoming the React testing standard due to its ease of use and opinionated approach.

If you're using React Testing Library, you can use a findBy query (docs), which waits up to 1000ms for an item to appear on the page.

It would look something like this:

import * from '@testing-library/react';

it('renders the fetched data', async () => {
    // Render the component with react testing library and
    // get the findByText() function to search the render
    const { findByText } = render(<MyComponent />);

    // Use the findBy function to wait up to 1000ms to find
    // the element that should appear after the fetch
    const elementImLookingFor = await findByText(/some text/)

    // Assert that it's in the rendered element
    expect(elementImLookingFor).toBeInTheDocument();
});

If you're not using React Testing Library, you can also manually use a 1000ms setTimeout() after rendering the element to wait a moment for it to finish fetching/loading before making your assertions.

I hope this helps!

Collapse
 
markskinsley profile image
Mark Skinsley

Hi Zak,

Thanks very much for the steer; React Testing Library seems to be the way to go for this sort of thing.

I think one issue I had was some of my packages were missing / out-of-date which was throwing some errors. In the end, after updating packages and importing @testing-library/jest-dom, I used this which seems to be working:

test('Data after re-render', async () => {
     render();
     expect(screen.queryByText(/test/)).toBeNull();
     expect(await screen.findByText(/test/)).toBeInTheDocument();
});

Thanks again,
Mark

Collapse
 
alanjereb profile image
Alan Jereb

To avoid mistakes and writing jest.resetAllMocks() after each test, you can use the following:

describe("My awesome test", () => {
    afterEach(() => {
       jest.resetAllMocks();
    });
    it("should do this and that", () => {
       ...
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tapaibalazs profile image
Tápai Balázs

Nice one!

I am going to try this out tomorrow. :)

I just want to mention that a false-negative test is a test which is green but it should not be.
A false-positive test is red but it should not be.

The test case where you don't mock Axios is not a false-negative but a false-positive one. :)