使用 Mocha 和 Chai 测试 Axios Redux 操作

Testing Axios Redux actions with Mocha and Chai

我正在尝试为使用 Axios 编写的用户登录功能编写测试。

函数是这样的:

export function signInUser({email, password}){
    return function(dispatch){
        axios.post(`${ROOT_URL}/signin`, {email, password})
        .then(response=>{
            dispatch({type:AUTH_USER});
            localStorage.setItem('token', response.data.token);
            browserHistory.push('/dashboard');
        })
        .catch(()=>{
            dispatch(authError('Bad login credentials'));
        });
    }
}

测试是这样的:

import {expect } from '../test_helper'
import { AUTH_USER, AUTH_ERROR, UNAUTH_USER, FETCH_MESSAGE, FETCH_PLOTS } from '../../src/actions/types';
import * as actions from '../../src/actions';
describe('actions',
    () => {
        describe('signInUser',
            () => {
                it('has the correct type',
                    () => {
                        const signin = actions.signInUser;
                        expect(signin.type).to.equal(AUTH_USER);
                    });
                it('has the correct payload',
                    () => {
                        const signin = actions.signInUser({
                            "email":"email@email.com",
                            "password":"pwd"
                        });
                        expect(action.payload).to.equal({
                            "email":"email@email.com",
                            "password":"pwd"
                        });
                    });
            });
    });

此测试失败,因为登录类型未定义。大概是因为返回的本身就是一个函数吧?我如何为这类事情编写适当的测试?研究这个东西,看来我需要设置一个叫做 mock 的东西,但是最简单的方法是什么?

我建议使用 axios-mock-adapter。测试您的 api 调用变得更加容易。

在每次测试之前,您可以 'mock' 请求,以便响应按照您喜欢的方式进行。