如何使用玩笑来测试axios拦截器?

时间:2018-11-26 16:54:06

标签: axios jestjs interceptor

我正在尝试测试以下代码:

import axios from 'axios';
import { history } from './ReduxService';

axios.interceptors.response.use(response => response,
    (error) => {
        if ((error.response && error.response.status === 408) || error.code === 'ECONNABORTED') {
            history.push('/error');
        }
        return Promise.reject(error);
    }
);

关于如何涵盖它的任何建议?

1 个答案:

答案 0 :(得分:0)

首先,修改代码,以便您可以在以下位置传递模拟版本的axios:

import axios, { AxiosInstance } from 'axios';
import { history } from './ReduxService';

export const addResponseInterceptor(client: AxiosInstance) => { 
    client.interceptors.response.use(response => response,
    (error) => {
        if ((error.response && error.response.status === 408) || error.code === 
        'ECONNABORTED') {
            history.push('/error');
        }
        return Promise.reject(error);
    });
};

然后按如下所示设置测试:

import { addResponseInterceptor } from './yourInterceptorFile'
import axios from 'axios';
jest.mock('axios', () => {
     return {
         create: jest.fn(),
         interceptors: {
             request: {
                 use: jest.fn(),
                 eject: jest.fn(),
             },
             response: {
                 use: jest.fn(),
                 eject: jest.fn(),
             },
         }
     };
});

describe('addResponseInterceptor tests', () => {
    
    beforeEach(() => {
        (axios.create as jest.Mock).mockReset();
        (axios.interceptors.request.use as jest.Mock).mockReset();
        (axios.interceptors.request.eject as jest.Mock).mockReset();
        (axios.interceptors.response.use as jest.Mock).mockReset();
        (axios.interceptors.response.eject as jest.Mock).mockReset();
    });
    it('should add a response interceptor to the axios instance', () => {
        addResponseInterceptor(axios);
        expect(axios.interceptors.response.use).toHaveBeenCalled();
    });
    it('should push to history when an error occurs', async() => {
        const historySpy = jest.spyOn(history, 'push');
        const axiosClient = axios;
        addResponseInterceptor(axios);
        const interceptorErrorHandler = (axiosClient.interceptors.response.use as jest.Mock).mock.calls[0][1];
        try {
            await interceptorErrorHandler({
                response: {
                    status: 408
                }
            });
            //this should not be called--the promise should be rejected
            expect(true).toBe(false);
         } catch {
            expect(historySpy).toHaveBeenCalledWith('/error');
         }
    });
    . . .
});