简体   繁体   English

如何模拟从单独模块导入的 Axios 实例?

[英]How do I mock an Axios Instance that is imported from a separate module?

In my react component I have:在我的反应组件中,我有:

import AxiosInstance from '../../common/ApiHandler'

where in ApiHandler.js I create an AxiosInstance在 ApiHandler.js 中我创建一个 AxiosInstance

AxiosInstance = axios.create(defaultOptions);

export default AxiosInstance;

I am trying to write a unit test for a function where this AxiosInstance does a post request.我正在尝试为 function 编写单元测试,其中此 AxiosInstance 执行发布请求。 Should I mock axios itself or should I mock the AxiosInstance imported into the react component?我应该模拟 axios 本身还是应该模拟导入到反应组件中的 AxiosInstance? How would I mock it so it returns some mock data?我将如何模拟它以便它返回一些模拟数据?

I originally tried the code below but this did not seem to return the data the way I wanted.我最初尝试了下面的代码,但这似乎没有按照我想要的方式返回数据。

jest.mock("axios", () => {
  return {
    create: jest.fn(() => {
      post: jest.fn(() => Promise.resolve(data: {mocked_data}))
    })
  }
});

I would always recommend creating mocks for the system under test.我总是建议为被测系统创建模拟。 Your component doesn't know about axios , only the AxiosInstance so that is what you should mock您的组件不知道axios ,只知道AxiosInstance所以这是您应该模拟的

import AxiosInstance from "../../common/ApiHandler";

jest.mock("../../common/ApiHandler", () => ({
  __esModule: true,
  default: { // add mock functions for whatever methods your component uses
    post: jest.fn(),
  },
}));

In your tests you can configure the responses.在您的测试中,您可以配置响应。 For example例如

// A successful response
AxiosInstance.post.mockResolvedValue({ data: mocked_data });

// A failed response
AxiosInstance.post.mockRejectedValue({ status: 400 });

Regarding __esModule: true , see the documentation ...关于__esModule: true ,请参阅文档...

When using the factory parameter for an ES6 module with a default export, the __esModule: true property needs to be specified.factory参数用于具有默认导出的 ES6 模块时,需要指定__esModule: true属性。


You could also create a more general manual mock of ApiHandler that can be re-used in any of your tests您还可以创建一个更通用的ApiHandler手动模拟,可以在您的任何测试中重复使用

// common/__mocks__/ApiHandler.js

export default {
  get: jest.fn(),
  post: jest.fn(),
};

Then your tests can use a simpler mock without a factory function然后您的测试可以使用没有工厂的更简单的模拟 function

import AxiosInstance from "../../common/ApiHandler";

jest.mock("../../common/ApiHandler");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM