我如何在开玩笑中测试axios [英] How do I test axios in jest
问题描述
我在反应中有这个动作
export function fetchPosts() {
const request = axios.get(`${WORDPRESS_URL}`);
return {
type: FETCH_POSTS,
payload: request
}
}
在这种情况下,如何测试axios?开玩笑说,在那个网站上有一个异步代码的用例,在那里他们使用了一个模拟函数,但是我不知道我是否可以用axios做到这一点?参考: https://facebook.github.io/jest/docs/tutorial-async .html
How do I test axios in this case? Jest have this use case on there site for async code where they use a mock function but I don't know if I can do this with axios? ref: https://facebook.github.io/jest/docs/tutorial-async.html
到目前为止,我已经进行了测试以测试它是否返回了正确的类型
I have done this so far to test that it is returning the correct type
it('should dispatch actions with the correct type', () => {
store.dispatch(fetchPosts());
let action = store.getActions();
expect(action[0].type).toBe(FETCH_POSTS);
});
我不知道如何传递模拟数据并测试它是否返回,但是,有人有任何想法吗?
I have no idea how to pass in mock data and test that it returns however, has anyone got any ideas?
提前谢谢
推荐答案
我使用了axios-mock-adapter. 在这种情况下,服务在./chatbot中描述. 在模拟适配器中,您可以指定使用API终结点时返回的内容.
I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.
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();
});
});
});
您可以在此处看到整个示例:
You can see it the whole example here:
服务: https://github.com/lnolazco/hutoma-test /blob/master/src/services/chatbot.js
测试: https://github.com/lnolazco/hutoma -test/blob/master/src/services/chatbot.test.js
这篇关于我如何在开玩笑中测试axios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!