Asynchronous Test Motivation
We want to ensure that the AUTHENTICATION_SUCCESS action is dispatched by our redux thunk middleware if the AUTHENTICATION_FAILED action is performed upon successful login if the login error is completed.
, Redux Thunk, Thunk Action.
Action Redux Thunk, API
- mock- unit test redux-thunk
- , , HTTP-, , . -, http-, .
- , HTTP.
nock, api .
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import nock from 'nock'
import expect from 'expect' // You can use any testing library
// modify these imports to suit your project
import * as actions from '../../actions/TodoActions'
import * as types from '../../constants/ActionTypes'
import {
AUTH_USER, AUTH_ERROR
} from './types';
const API_URL = 'www.api-example.com'
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)
describe('async actions', () => {
afterEach(() => {
nock.cleanAll()
})
it('creates AUTH_USER action when user is logged in', () => {
nock(API_URL)
.post(/auth/login)
.reply(200, { data: 'Logged in successfully'] }})
const expectedActions = [
{ type: AUTH_USER }
]
const store = mockStore({ })
return store.dispatch(actions.loginUser({'example@x.com','password'}))
.then(() => { // return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
})
it('creates AUTH_ERROR if user login fails', () => {
nock(API_URL)
.post(/auth/login)
.reply(404, { data: {error: 404 }] }})
const expectedActions = [
{ type: AUTH_ERROR }
]
const store = mockStore({ })
return store.dispatch(actions.loginUser({'example@x.com','password'}))
.then(() => { // return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
})
})
, , return , thunk.
, , axios.post, .then , , , .
Thunk
import axios from 'axios';
import { browserHistory } from 'react-router';
import { API_URL } from 'config';
import {
AUTH_USER
} from './types';
export function loginUser({ email, password }) {
return function (dispatch) {
return axios.post(`${API_URL}/auth/login`, { email, password })
.then((response) => {
dispatch({ type: AUTH_USER });
localStorage.setItem('token', response.data.token);
browserHistory.push('/feature');
})
.catch(() => {
dispatch(authError('Bad Login Info'));
});
};
}