使用 jest.mock('axios') 时如何模拟拦截器? [英] How to mock interceptors when using jest.mock('axios')?

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

问题描述

使用 jest 运行测试时,我有基本的测试服语法:

When running a test using jest I have the basic test suit syntax:

jest.mock('axios');

describe('app', () => {
    let render

    beforeEach(() => {
        axiosMock.get.mockResolvedValueOnce({
            data: {greeting: 'hello there'},
        }),
        render= renderApp()
    });

    test('should render something', () => {
        expect(something).toBeInTheDocument();
    });


});

问题是我的代码中有拦截器,当使用 jest 命令输出运行测试时:

The problem is I have interceptors in my code which when running the test with jest command outputs:

类型错误:无法读取未定义的属性拦截器"

并指向拦截器对象

axiosInstance.interceptors.request.use(...

axiosInstance 是存储axios.create

export const axiosInstance = axios.create({...

参考这个 axios 线程在 SO 我如何在玩笑中测试 axios 但它不涉及任何拦截器所以没有真正的帮助.

Refered to this axios thread on SO How do I test axios in jest but it doesn't involve any interceptors so didn't really help.

推荐答案

到此就够了,简单明了 jest.fn()

This was enough in the end, plain and simple jest.fn()

jest.mock('axios', () => {
    return {
        interceptors: {
            request: { use: jest.fn(), eject: jest.fn() },
            response: { use: jest.fn(), eject: jest.fn() },
        },
    };
});

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

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