我创建了一个 axios 实例...
// api/index.js
const api = axios.create({
baseURL: '/api/',
timeout: 2500,
headers: { Accept: 'application/json' },
});
export default api;
和几个模块使用它..
// 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 是未定义的?
最佳答案
对于任何仍在为此苦苦挣扎的人。
您需要确保初始化您的 MockAdapter
在测试机构之外。
IE。
❌ 不正确 ❌
it('should do a thing', () => {
const mockAdapter = new MockAdapter(axios);
})
✅ 正确 ✅const mockAdapter = new MockAdapter(axios);
it('should pass' () => {})
关于unit-testing - 使用 axios-mock-adapter 模拟 axios 得到未定义的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296809/