相关疑难解决方法(0)

如何模拟 axios.create([config]) 函数以返回其实例方法而不是用模拟覆盖它们?

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

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

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

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

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

我怎样才能获得 axiosInstance 变量中的所有实例方法,而不是只有一个什么都不做的模拟函数?

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

javascript unit-testing jestjs axios react-testing-library

2
推荐指数
1
解决办法
4200
查看次数