我有一个配置axios的模块:
// config/axiosConfig.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:8080/api/v1'
});
export default instance;以及一个模块,该模块使用它进行api调用:
// store/actions.ts
import axiosInstance from 'config/axiosConfig';
export const fetchUsers = () => (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
dispatch(loading(true));
return axiosInstance.get('/users')
.then(res => {
dispatch(loading(false));
dispatch(fetched(res.data));
})
.catch(err => dispatch(error(true)));
}
...我想模拟axios配置文件来测试我的api文件。我试过很多种方法,但都没有用。我以为这会很简单
// store/actions.test.ts
import axiosInstance from 'config/axiosConfig';
jest.mock('config/axiosConfig');
axiosConfig.get.mockResolvedValue({users: mockUserList});
...但我想事情不是这样的。
编辑:当我将axiosConfig.get.mockResolvedValue({users: mockUserList});放在测试中,而不是在模拟调用下时,问题中的方法就会奏效。
发布于 2020-12-18 14:56:40
试一试(将它放在文件的顶部或beforeAll或beforeEach内部的顶部,取决于您喜欢什么):
jest.mock('config/axiosConfig', () => ({
async get(urlPath) {
return {
users: mockUserList,
};
},
}));这是一个使用工厂函数的简单模拟。为了在任何地方使用模拟,jest提供了一种更好的方法来避免重复自己。创建一个__mocks__目录,在该目录中,您可以创建模块,然后覆盖许多内置程序。然后,您可以只使用下面的代码就可以了。
// file.test.ts
jest.mock('fs')
// Rest of your testing code below看一看官方文件,了解更多有关这方面的信息。
如果这不起作用,那么jest.config.js和tsconfig.js中的模块解析设置可能会有所不同。
https://stackoverflow.com/questions/65354705
复制相似问题