为什么TypeError:axios.create不是函数?测试axios GET时 [英] Why TypeError: axios.create is not a function? When testing axios GET
问题描述
我正在尝试在React中测试我的axios API函数.
I'm trying to test my axios API functions in React.
在这里发现了这个问题:如何在笑话中测试axios 指向使用axios-mock-adapter
Found this question here: how do i test axios in jest which pointed to using axios-mock-adapter
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import chatbot from './chatbot';
describe('Chatbot', () => {
it('returns data when sendMessage is called', done => {
var mock = new MockAdapter(axios);
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
chatbot.sendMessage(0, 'any').then(response => {
expect(response).toEqual(data);
done();
});
});
});
真正的功能:
The real function:
/**
* Retrieve all Akamai images
* @param {String} akamai Akamai url
* @return {Thenable} Resolved: Akamai images
*/
export const callGetAkamai = () =>
makeRequest('/akamai', 'GET')
.catch(defaultCatch('callGetAkamai'));
我的测试:
import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { callGetAkamai } from './api';
describe('GetAkamai', () => {
it('returns data when callGetAkamai is called', (done) => {
console.log('MockAdapter', MockAdapter);
const mock = new MockAdapter(axios);
// const mock = axios.create({
// baseURL: 'https://us-central1-hutoma-backend.cloudfunctions.net/chat/'
// });
const data = { response: true };
mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data);
callGetAkamai().then((response) => {
expect(response).toEqual(data);
done();
});
});
});
推荐答案
您是否在嘲笑axios
?我自己遇到了这个问题,在所有错误的地方查看后,我意识到我已经在用jest
嘲笑axios
了.
Are you mocking axios
already? I have run into this issue myself, and after looking in all the wrong places, I realized I was already mocking axios
with jest
.
在您的 setupTestFrameworkScriptFile 中放置以下代码段:
Put the following snippet in your setupTestFrameworkScriptFile:
const mockNoop = () => new Promise(() => {});
// Notice how `create` was not being mocked here...
jest.mock('axios', () => ({
default: mockNoop,
get: mockNoop,
post: mockNoop,
put: mockNoop,
delete: mockNoop,
patch: mockNoop
}));
虽然您可以同时执行两项操作,但是如果您正在使用axios-mock-adapter
,则可能要删除其他模拟(并跳过上面的代码段).
While you might be able to do both, if you are using the axios-mock-adapter
, you might want to remove your other mocks (and skip the snippet above).
这篇关于为什么TypeError:axios.create不是函数?测试axios GET时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!