Boris K
Boris K

Reputation: 3580

Testing Axios Redux actions with Mocha and Chai

I'm trying to write a test for a user signin function written with Axios.

The function is this:

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'));
        });
    }
}

The test is this:

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 protected]",
                            "password":"pwd"
                        });
                        expect(action.payload).to.equal({
                            "email":"[email protected]",
                            "password":"pwd"
                        });
                    });
            });
    });

This test is failing, because the signin type is undefined. Presumably, because what is returned is itself a function? How do I write a proper test for this sort of thing? Researching this thing, it looks like I need to set up something called a mock, but what's the simplest way to do it?

Upvotes: 0

Views: 407

Answers (1)

Hemerson Carlin
Hemerson Carlin

Reputation: 7424

I'd recommend using axios-mock-adapter. It gets easier to test your api calls.

Before each test, you can 'mock' the requests so the responses behave the way you like them to.

Upvotes: 1

Related Questions