本文介绍了开玩笑的mockResolvedValue不是一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模拟api调用时出现错误

I'm getting an error mocking my api call

TypeError: Cannot read property 'mockResolvedValue" of undefined

,无法弄清原因.我正在利用玩笑来测试我的api提取调用功能.

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

这是我要导出的功能:

//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;

这是我的测试文件

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

我得到的错误:

推荐答案

由于您已经模拟了axios类,因此模拟axios.get返回值的一种方法是执行以下操作:

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);

或者,您可以监视axios.get()并提供模拟的返回值:

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

这篇关于开玩笑的mockResolvedValue不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 11:28