【问题标题】:Mock axios using axios interceptors使用 axios 拦截器模拟 axios
【发布时间】:2019-06-26 06:03:33
【问题描述】:

我正在尝试使用 mockAxios 来测试 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);
        }
    );
}

当我创建 mockAxios 时:

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

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

那么如何使用 axios 拦截器和 mockAxios 进行测试呢?

【问题讨论】:

  • 请再次格式化代码并相应地edit。在提交之前使用预览确保结果看起来正确。
  • 有什么解决办法吗?

标签: mocking jestjs axios


【解决方案1】:

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

这就是我的做法:

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

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

【讨论】:

    【解决方案2】:

    这就是我的成就

    Interceptor.js

    /* Module that I want to test
     * Intercepts every axios request and redirects to login on 401
     */
    
    import axios from 'axios';
    
    export default () => {
      axios.interceptors.response.use(
        response => {
          // Return a successful response back to the calling service
          return response;
        },
        error => {
          // Return any error which is not due to authentication back to the calling service
          if (error.response.status !== 401) {
            return new Promise((resolve, reject) => {
              reject(error);
            });
          } else {
            window.location.href = '/operator-portal/login';
            return false;
          }
        }
      );
    };
    

    Interceptor.test.js

    import axios from 'axios';
    import interceptor from '../../src/apis/interceptor';
    
    jest.mock('axios');
    
    describe('interceptor', () => {
      it('redirects to login route when response status is 401', () => {
        delete global.window.location;
        global.window = Object.create(window);
        Object.defineProperty(window, 'location', {
          value: {
            href: 'url'
          }
        });
        axios.interceptors.response.use = jest.fn((successCb, failCb) => {
          failCb({
            response: {
              status: 401
            }
          });
        });
        interceptor();
        expect(window.location.href).toEqual('/login');
      });
    
      it('redirects to login route when success handler is called', () => {
        axios.interceptors.response.use = jest.fn(successCb => {
          successCb();
        });
        interceptor();
        window.location.href = 'url';
        expect(window.location.href).toEqual('url');
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2020-06-10
      • 2019-03-15
      • 2018-11-27
      • 2022-11-09
      • 2020-01-19
      • 2020-08-31
      • 2023-04-06
      • 2021-05-10
      • 1970-01-01
      相关资源
      最近更新 更多