使用axios拦截器模拟axios

14

我正在尝试使用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没有返回响应,它可以只返回一个普通对象。

那么我该如何在测试中使用mockAxios来使用axios拦截器呢?


请重新尝试格式化代码并进行编辑。在提交之前,请使用预览确保结果看起来正确。 - jonrsharpe
有什么解决方案吗? - four-eyes
2个回答

3
这是我实现的方法:
拦截器.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');
  });
});

0

为什么不使用标准的jest mocking来模拟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 调用都将根据你的实现进行模拟。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接