The open blogging platform. Say no to algorithms and paywalls.

Creating Axios mock requests in Jest

How to create your own reusable axios mock request function for Jest.

image

Let's say I have a method named loadData which is responsible to load data from an REST get endpoint.

loadData = () => {
    Axios.get(“https://jsonplaceholder.typicode.com/users")
}

Now we want to write test on it.

Let's write some test on this method.

Test 1: Method implemented

expect(instance.loadData).toBeDefined()//Instance is your class or component shallow instance

Test 2: Now let's create a mock axios response to see this method return something.

import axios from "axios";
jest.mock("axios") //Add this on top of your test file.

Now lets make the loadData as async

loadData = async ()=>{
    Axios.get(“https://jsonplaceholder.typicode.com/users")
}

Let's consider our mockAxios return some data like

 {data:”some data”}

So our method loadData will return same data as response.

Our test would be like:

axios.get.mockResolvedValue({data:"some data"});
const result = await instance.loadData()
expect(result).toEqual({data:”some data”})

Test 3: This test covers the catch case of axios with mockRejectedValue.

axios.get.mockRejectedValue({error:"some error"});
  await instance.loadData().catch(err => {
  expect(err).toEqual({error:”some error”});
})

Now it's done!




Continue Learning