使用axios拦截器模拟axios [英] Mock axios using axios interceptors

查看:212
本文介绍了使用axios拦截器模拟axios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mockAxios与axios拦截器进行测试.

I'm trying to use mockAxios for testing with axios interceptors.

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时:

When I created mockAxios:

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

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

All of my tests failed with the follow message: cannot read property response of undefined inside of axios interceptors. It happens because mock axios doesn't return response. It could just return a plain object.

那我该如何将axios拦截器与mockAxios一起使用进行测试?

So how can I use axios interceptors with mockAxios for testing?

推荐答案

这是我的实现方式

Interceptor.js

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

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

这篇关于使用axios拦截器模拟axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆