Boris K Boris K - 3 years ago 339
React JSX Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download