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

查看:26
本文介绍了如何模拟 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天全站免登陆