Umair Umair - 3 months ago 33
React JSX Question

React-redux: How to write an integration test

I am using

Enzyme
to test my react and redux portions. I've read around and have found that its a good practice to write an integration test for the component as well.
So, that's simple as I have to call the action creators and check their updated values against store but I have some async actions that return
dispatch
actions.

login.actions.js

export function loginUser(credentials) {
return dispatch => {
dispatch(action.loginRequest());
return axios({
method: 'post',
url: `${api}/login`,
data: {
email: _.trim(_.get(credentials, 'email')),
password: _.get(credentials, 'password')
}
})
.then(response => {
const { data } = response;

if (_.isEqual(_.get(response, 'status'), 200)) {
dispatch(action.loginSuccess(data));
}
})
.catch(err => {
dispatch(action.loginError(err));
});
};
}


login.actionCreators.js

export function loginRequest() {
return {
type: types.LOGIN_REQUEST
};
}
export function loginSuccess(payload) {
return {
type: types.LOGIN_SUCCESS,
payload
};
}
export function loginError(payload) {
let error;
switch (_.get(payload, 'response.status')) {
case 422: {
error = 'Invalid Credentials';
break;
}
case 401: {
error = 'Invalid user';
break;
}
case 403: {
error = 'Account not confirmed';
break;
}
default:
error = 'Something went wrong';
}
return {
type: types.LOGIN_ERROR,
error
};
}


So, in order to perform a complete integration test, I would have to test the
login.actions.js
as well but since dispatch normally returns plain objects, in my case they are returning a dispatch function. How do I test them?

Answer

It is simple to test async actions.

I am using moxios ans sinon. You can basically extend this to all different cases and test it in the same pattern

import moxios from 'moxios';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { spy } from 'sinon';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('async actions', () => {
  beforeEach(() => {
    moxios.install();
  });

  afterEach(() => {
    moxios.uninstall();
  });
  it(`should create action LOGIN_SUCCESS after successful login`, () => {
    moxios.wait(() => {
      const request = moxios.requests.mostRecent();
      request.respondWith({
        status: 200,
        response: { message: 'success', status: '200' },
      });
    });
    const expectedActions = [
      { type: types.LOGIN_REQUEST },
      { type: types.LOGIN_SUCCESS, data: { message: 'success', status: '200' } },
    ];
    const store = mockStore({ auth: {} });
    return store.dispatch(loginUser('abcd', '1234'))
    .then(() => {
      expect(store.getActions()).to.eql(expectedActions);
    });
  });
});
Comments