How To Mock API Calls In Jest


2 min read

This is a quick blog on how I used jest.mock to create a mock of an ES6 class, in my weather manager app.

What Are Mocks?

Mock objects are simulated objects that mimic the behaviour of real objects in controlled ways. — https://en.wikipedia.org/wiki/Mock_object

In my weather manager, I have two classes:

  • APIRequest: contains functions with API calls to openweathermap.org

  • Weather: formats the data received from the API calls

To the best of my knowledge, the purpose of using a mock for the APIRequest class is to ensure when tests for the Weather class methods (which include calls to methods in the APIRequest class) are run, actual API calls are not made.


Jest Mocks

The JavaScript testing library, Jest, has the option to mock ES6 classes.

In my app, when an instance of the Weather class is initialised, it creates a new instance of the APIRequest class, setting it to this.apiRequest:

1export class Weather {
2 constructor() {
3 ...
4 this.apiRequest = **new APIRequest()**;
5 }

Using the getOneDayWeather function in the Weather class as an example, this method calls weatherOneDay() in the APIRequest class when it is invoked:

1async getOneDayWeather() {
2 const todayWeather = await this.**apiRequest.weatherOneDay()**;
3 return todayWeather;
4 }

To simulate the APIRequest function weatherOneDay() being called in the tests, the APIRequest class can be set as a mock. This is inputted before any tests relating to API calls:

1jest.mock('../src/api_request')
2
3...
4
5beforeEach(() => {
6 APIRequest.mockClear();
7});

The test below checks if calling the Weather function getOneDayWeather also calls the APIRequest function weatherOneDay:

1jest.mock('../src/api_request')
2
3it('checks if getOneDayWeather calls the APIRequest method weatherOneDay', () => {
4 const weather = new Weather();
5 weather.getOneDayWeather();
6 const mockAPIRequestInstance = APIRequest.mock.instances[0];
7 const mockWeatherOneDay = mockAPIRequestInstance.weatherOneDay;
8 expect(mockWeatherOneDay).toHaveBeenCalledTimes(1);
9});

To clarify the above, a mock instance of the APIRequest class is set to mockAPIRequestInstance:

1const mockAPIRequestInstance = APIRequest.mock.instances[0]

A mock instance of the APIRequest method weatherOneDay is created with:

1const mockWeatherOneDay = mockAPIRequestInstance.weatherOneDay

This test is checking that the mock instance of the weatherOneDay method has been called once after weather.getOneDayWeather() is called:

1expect(mockWeatherOneDay).toHaveBeenCalledTimes(1)

And that’s how I used jest.mock to mock an API call in a test 🥳


Helpful Resources

Previous post:
How To Deploy A Web App To Heroku
Next post:
What Is The Single Responsibility Principle?

Discussion