javascript - 使用 jest 模拟多个 axios 调用
问题描述
我刚刚发现了这种使用 jest 模拟 axios 的有用方法,但是,如果我多次调用具有不同 url 的 axios,我如何指定 url 和根据 url 返回的值?有没有办法在不使用 3rd 方库的情况下做到这一点?
谢谢
// users.test.js
import axios from 'axios';
import Users from './users';
jest.mock('axios');
test('should fetch users', () => {
const users = [{name: 'Bob'}];
const resp = {data: users};
axios.get.mockResolvedValue(resp);
// or you could use the following depending on your use case:
// axios.get.mockImplementation(() => Promise.resolve(resp))
return Users.all().then(data => expect(data).toEqual(users));
});
解决方案
您可以在.mockImplementation()
回调中处理多个条件:
jest.mock('axios')
axios.get.mockImplementation((url) => {
switch (url) {
case '/users.json':
return Promise.resolve({data: [{name: 'Bob', items: []}]})
case '/items.json':
return Promise.resolve({data: [{id: 1}, {id: 2}]})
default:
return Promise.reject(new Error('not found'))
}
})
test('should fetch users', () => {
return axios.get('/users.json').then(users => expect(users).toEqual({data: [{name: 'Bob', items: []}]}))
})
test('should fetch items', () => {
return axios.get('/items.json').then(items => expect(items).toEqual({data: [{id: 1}, {id: 2}]}))
})
推荐阅读
- r - 对于`Petal.Length`的固定值和`Species`,如何绘制`Sepal.Length`和`Sepal.Width`之间的关系?
- android - 当设备在 react-native 中离线时,在 webview 中显示本地图像
- javascript - 为文本框创建一个刷新按钮
- linux - ioctl 中的命令 21505 是什么意思?
- reactjs - 如何解决这个元素类型是反应中的无效错误?
- flutter - 如何在 Appbar Flutter 中定位项目
- javascript - 根据 typeScript 中的多个条件过滤对象数组
- java - 将 rx observable api 调用转换为 kotlin 协程
- javascript - Angular 在搜索字段和搜索结果中记住最新的输入数据
- machine-learning - 如何区分填充xgboost的特征真值0和缺失值0?