如何在 Jest 中测试 axios?

2022-01-31 00:00:00 axios reactjs javascript jestjs react-redux

我在 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

相关文章