我如何在 Jest 中测试 axios? [英] How do I test axios in Jest?

查看:52
本文介绍了我如何在 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆