使用axios拦截器模拟axios

Dat*_* Vu 9 mocking axios

我正在尝试使用嘲笑axios与axios拦截器进行测试。

export default {
    get: jest.fn(() => Promise.resolve({ data: {} }))
}

import axios from 'axios';

export const configurateAxios = () => {
    axios.interceptors.response.use(
        response => {
          return response;
        },
        error => {
          return Promise.reject(error);
        }
    );
}
Run Code Online (Sandbox Code Playgroud)

当我创建了mockAxios时:

export default {
    get: jest.fn(() => Promise.resolve(data: {}))
}
Run Code Online (Sandbox Code Playgroud)

我所有的测试均失败,并显示以下消息:无法读取axios拦截器内部未定义的属性响应。这是因为模拟axios不会返回响应。它可能只返回一个普通对象。

那么,如何将axios拦截器与mockAxios一起进行测试?

Luc*_*a T 0

为什么不get()使用标准的玩笑模拟来模拟 axios 方法?

这就是我的做法:

// Define how I want my mocked `get` to behave
const axiosMockedGet = async () => {
    return {
        data: 'the response from the GET request'
    };
};

// Mock axios
jest.mock('axios', () => {
    return jest.fn().mockImplementation(() => {
        return {
            // Inject a function named `get`
            get: sessionFunctionMock
        };
    });
});
Run Code Online (Sandbox Code Playgroud)

此后,所有对 axios' 的调用都get应该根据您的axiosMockedGet实现进行模拟。