Eug*_*nic 2 javascript unit-testing jestjs axios react-testing-library
我正在尝试模拟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
您可以使用 jest 的genMockFromModule。它将jest.fn()为每个模块的方法生成,您将能够使用.mockReturnThis()oncreate返回相同的实例。
./src/__mocks__/axios.js
const axios = jest.genMockFromModule('axios');
axios.create.mockReturnThis();
export default axios;
Run Code Online (Sandbox Code Playgroud)
工作示例
从Jest 26.0.0+它重命名为jest.createMockFromModule
| 归档时间: |
|
| 查看次数: |
4200 次 |
| 最近记录: |