gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:39:15 24 4
gpt4 key购买 nike

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

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

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

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

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

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

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

最佳答案

您可以使用 jest 的 genMockFromModule .它将为每个模块的方法生成 jest.fn(),您将能够在 create 上使用 .mockReturnThis() 来返回相同的实例。

例子:

./src/__mocks__/axios.js
const axios = jest.genMockFromModule('axios');

axios.create.mockReturnThis();

export default axios;
working example

编辑:

Jest 26.0.0+ 重命名为 jest.createMockFromModule

关于javascript - 如何模拟 axios.create([config]) 函数以返回其实例方法而不是用模拟覆盖它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60428640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com