使用axios-mock-adapter模拟axios获得未定义的响应 [英] Mock axios with axios-mock-adapter get undefined resp
本文介绍了使用axios-mock-adapter模拟axios获得未定义的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个axios实例...
I created an axios instance ...
// api/index.js
const api = axios.create({
baseURL: '/api/',
timeout: 2500,
headers: { Accept: 'application/json' },
});
export default api;
还有几个模块使用它..
And severals modules use it ..
// api/versions.js
import api from './api';
export function getVersions() {
return api.get('/versions');
}
我尝试像..
// Test
import { getVersions } from './api/versions';
const versions= [{ id: 1, desc: 'v1' }, { id: 2, desc: 'v2' }];
mockAdapter.onGet('/versions').reply(200, versions);
getVersions.then((resp) => { // resp is UNDEFINED?
expect(resp.data).toEqual(versions);
done();
});
为什么resp未定义?
Why resp is undefined?
推荐答案
您不需要axios-mock-adapter
.这是我模拟我的axios
:
You don't need axios-mock-adapter
. Here is how I mock my axios
:
// src/__mocks__/axios.ts
const mockAxios = jest.genMockFromModule('axios')
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios
有关更多信息: https://stackoverflow.com/a/51414152/73323
这篇关于使用axios-mock-adapter模拟axios获得未定义的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文