How do I test axios in Jest?(如何在 Jest 中测试 axios?)
问题描述
我在 React 中有这个动作:
I have this action in React:
export function fetchPosts() {
const request = axios.get(`${WORDPRESS_URL}`);
return {
type: FETCH_POSTS,
payload: request
}
}
在这种情况下我如何测试 Axios?
How do I test Axios in this case?
Jest 在他们的网站上有一个异步代码用例,他们使用模拟函数,但我可以用 Axios 做到这一点吗?
Jest has this use case on their site for asynchronous code where they use a mock function, but can I do this with Axios?
参考:一个异步示例
到目前为止,我已经这样做了,以测试它是否返回了正确的类型:
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);
});
如何传入模拟数据并测试它是否返回?
How can I pass in mock data and test that it returns?
推荐答案
我用过 axios-模拟适配器.在这种情况下,服务在 ./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
这篇关于如何在 Jest 中测试 axios?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Jest 中测试 axios?


基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 动态更新多个选择框 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01