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

Ros*_*kyi 5 interceptor jestjs axios

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

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);
    }
);
Run Code Online (Sandbox Code Playgroud)

关于覆盖范围有什么建议吗?

小智 1

首先,修改代码,以便可以在以下位置传递 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);
    });
};
Run Code Online (Sandbox Code Playgroud)

然后像这样设置你的测试:

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');
         }
    });
    . . .
});
Run Code Online (Sandbox Code Playgroud)