22

I'm getting an error mocking my api call

TypeError: Cannot read property 'mockResolvedValue" of undefined

and cannot figure out why. I'm utilizing jest to test my api fetch call function.

This is my function I'm exporting:

//file amData.jsx

const axios = require('axios');

async function fetchAssetManagerSummary() {
  const response = await axios.get("https://www.exampleUrl.com");
  return response.data;
}

module.exports = fetchAssetManagerSummary;

This is my test file

const fetchAssetManagerSummary = require('./amData');
const axios = require('axios');
jest.mock("axios");

it("returns the object from fetch", async () => {
  axios.get.mockResolvedValue({
    data: [
      {
        userId: 1,
        id: 1,
        title: 'test'
      }
    ]
  })
  const data = await fetchAssetManagerSummary();
  console.log("data", data)
});

The error I'm getting:

enter image description here

pt2t
  • 431
  • 1
  • 7
  • 16
  • "Cannot read property 'mockResolvedValue" of undefined" is very different from what's stated in the title of the question. Please correct the title. – MEMark May 16 '21 at 18:54

1 Answers1

30

Since you have already mocked the axios class, one of the ways of mocking the return value of axios.get is to do this:

axios.get = jest.fn().mockResolvedValue({
  data: [
    {
      userId: 1,
      id: 1,
      title: 'test'
    }
  ]
});
.
.
expect(axios.get).toHaveBeenCalledTimes(1);

Alternatively, you can spy on axios.get(), and provide a mocked return value:

jest.spyOn(axios, 'get').mockResolvedValueOnce({
  data: [
    {
      userId: 1,
      id: 1,
      title: 'test'
    }
  ]
});
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • 18
    Why doesn't mocking as the original question does work since that is exactly what the jest documentation says to do: https://jestjs.io/docs/en/mock-functions#mocking-modules – Joelle Boulet Dec 24 '20 at 16:40
  • 6
    I have the exact same issue and no idea why it is not actually working as per documentation – Potter Rafed Jan 29 '21 at 12:23