我有这个反应
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
到目前为止,我已经测试了它是否返回了正确的类型
it('should dispatch actions with the correct type', () => { store.dispatch(fetchPosts()); let action = store.getActions(); expect(action[0].type).toBe(FETCH_POSTS); });
我不知道如何传递模拟数据并测试它是否返回,但是有人有任何想法吗?
先感谢您
我使用了axios-mock-adapter。在这种情况下,服务在./chatbot中描述。在模拟适配器中,您指定使用API端点时返回的内容。
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(); }); }); });
您可以在此处查看整个示例:
服务: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