Jest mockResolvedValue is not a function

痞子三分冷 提交于 2021-01-27 06:04:38

问题


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://fr-assetmanager.azurewebsites.net/File/GetOverview?runDat=04/01/2020");
  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:


回答1:


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'
    }
  ]
});


来源:https://stackoverflow.com/questions/61627298/jest-mockresolvedvalue-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!