首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在使用jest.mock('axios')时模拟拦截器?

如何在使用jest.mock('axios')时模拟拦截器?
EN

Stack Overflow用户
提问于 2020-02-26 09:35:00
回答 3查看 25.3K关注 0票数 13

在使用jest运行测试时,我具有基本的测试适应语法:

代码语言:javascript
复制
jest.mock('axios');

describe('app', () => {
    let render

    beforeEach(() => {
        axiosMock.get.mockResolvedValueOnce({
            data: {greeting: 'hello there'},
        }),
        render= renderApp()
    });

    test('should render something', () => {
        expect(something).toBeInTheDocument();
    });


});

问题是我的代码中有拦截器,当使用jest命令输出运行测试时:

TypeError:无法读取未定义的属性“拦截器”

并指向拦截器对象。

axiosInstance.interceptors.request.use(...

axiosInstance是存储axios.create返回的变量。

export const axiosInstance = axios.create({...

引用这个公理线程所以How do I test axios in jest,但它不涉及任何拦截器,所以没有真正的帮助。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-02-27 07:59:26

这就足够了,简单明了的jest.fn()

代码语言:javascript
复制
jest.mock('axios', () => {
    return {
        interceptors: {
            request: { use: jest.fn(), eject: jest.fn() },
            response: { use: jest.fn(), eject: jest.fn() },
        },
    };
});
票数 17
EN

Stack Overflow用户

发布于 2020-02-26 12:17:18

如果使用了拦截器和axios.create,请确保模拟:

代码语言:javascript
复制
// Replace any instances with the mocked instance (a new mock could be used here instead):
axios.create.mockImplementation((config) => axios);

// Mock out the interceptor (assuming there is only one):
let requestCallback = () => {
  console.log("There were no interceptors");
};
axios.interceptors.request.use.mockImplementation((callback) => {
  requestCallback = callback;
});

// Mock out the get request so that it returns the mocked data but also calls the 
// interceptor code:
axios.get.mockImplementation(() => {
  requestCallback();
  return {
    data: "this is some data"
  };
});

如果这不起作用,Note

本例假设创建和拦截器调用位于Jest可以模拟它们的位置。将axios.createaxiosInstance.interceptors.request.use行放置在函数范围之外可能会导致上述模拟失败。这是一个示例文件,Jest可以在其中模拟它们:

代码语言:javascript
复制
const axios = require('axios');

const DEBUG = true;

const customRequest = (url) => {
  // Example of axios.create from https://www.npmjs.com/package/axios#axioscreateconfig
  const axiosInstance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
  });

  // Example of interceptor taken from https://stackoverflow.com/a/52737325/7470360:
  axiosInstance.interceptors.request.use((config) => {
    if (DEBUG) { console.info("Request called", config); }
    return config;
  }, (error) => {
    if (DEBUG) { console.error("Request error ", error); }
    return Promise.reject(error);
  });

  return axiosInstance.get(url);
}

module.exports = customRequest;

模拟代码将模拟axios.create调用和customRequest中的axiosInstance调用。将创建或拦截移到函数之外将导致模拟失败。

票数 7
EN

Stack Overflow用户

发布于 2021-05-11 18:24:17

下面是我如何嘲笑axios.create和它的interceptors

代码语言:javascript
复制
jest.mock('axios', () => {
  return {
    create: () => {
      return {
        interceptors: {
          request: {eject: jest.fn(), use: jest.fn()},
          response: {eject: jest.fn(), use: jest.fn()},
        },
      };
    },
  };
});

之后,我能够在我的测试代码中调用以下内容:

代码语言:javascript
复制
const client = axios.create({
  baseURL: 'http://some-url.com',
});

client.interceptors.request.use(config => {
  // some other test code
  return config;
});
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60410731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档