如何模拟axios.create([config])函数以返回其实例方法,而不是用模拟覆盖它们? [英] How to mock axios.create([config]) function to return its instance methods instead of overriding them with mock?

查看:621
本文介绍了如何模拟axios.create([config])函数以返回其实例方法,而不是用模拟覆盖它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟 axios.create(),因为我正在整个应用程序中使用其实例,显然需要其所有实现,该实现已被模拟破坏,因此无法获得结果正确的get,post方法.

I'm trying to mock axios.create() because I'm using its instance across the app and obviously need all of its implementation which is destroyed by the mock, thus cannot get the result of the get, post method properly.

这是代码在实际文件中的样子:

This is how the code looks like in the actual file:

 export const axiosInstance = axios.create({
        headers: {
           ...headers
        },
        transformRequest: [
            function (data, headers) {
                return data;
            },
        ],
    });
    const response = await axiosInstance.get(endpoint);

这是测试文件中axios的模拟设置

And here is the mock setup for axios inside the test file

   jest.mock('axios', () => {
        return {
            create: jest.fn(),
            get: jest.fn(() => Promise.resolve()),
        };
    }
);

我如何才能在axiosInstance变量中获取所有实例方法,而不是仅仅具有不执行任何操作的模拟功能?

How could I get all of the instance methods in the axiosInstance variable instead of just having a mock function which does nothing?

axios.create和实例方法的文档: https://github.com/axios/axios#instance-methods

Documentation for axios.create and instance methods: https://github.com/axios/axios#instance-methods

推荐答案

最终坚持使用axios模拟,并通过将axiosInstance指针分配给已创建的axios模拟来指向该模拟. 基本上是 @jonrsharpe 建议的

Ended up sticking with the axios mock and just pointing to that mock by assigning the axiosInstance pointer to created axios mock. Basically as @jonrsharpe suggested

简而言之:

import * as m from 'route';
jest.mock('axios', () => {
        return {
            create: jest.fn(),
            get: jest.fn(() => Promise.resolve()),
        };
    }
);
m.axInstance = axios

如果我可以不用它,那会很好.

Would be very nice though if I could have gone without it.

这篇关于如何模拟axios.create([config])函数以返回其实例方法,而不是用模拟覆盖它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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