Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test async Redux actions to mock ajax response

I am creating a middleware for making ajax requests using async actions. The middleware intercepts original action, performs ajax request, and re-dispatches the original action along with the response from the url.

So, my Component would merely dispatch an action like this

onClick() {
    dispatch(ActionCreator.fetchUser());
}

Rest will be taken care by the middleware as shown here.

My question is, what should I do for unit testing? Should I mock the onClick itself? or I should write a mocked middleware and forward the actions with the mocked response?

I am not sure which approach should I take. I tried several stuff, but none of what I tried made sense to me.

Any pointers?

like image 687
Salman Avatar asked Oct 08 '15 09:10

Salman


2 Answers

Note: answer below is slightly outdated.

A much simpler updated approach is described here.
You can still do it the other way too, though.


We now have a section on testing async action creators in the official docs.

For async action creators using Redux Thunk or other middleware, it’s best to completely mock the Redux store for tests. You can still use applyMiddleware() with a mock store, as shown below. You can also use nock to mock the HTTP requests.

function fetchTodosRequest() {
  return {
    type: ADD_TODOS_REQUEST
  };
}

function fetchTodosSuccess(body) {
  return {
    type: ADD_TODOS_SUCCESS,
    body
  };
}

function fetchTodosFailure(ex) {
  return {
    type: ADD_TODOS_FAILURE,
    ex
  };
}

export function fetchTodos(data) {
  return dispatch => {
    dispatch(fetchTodosRequest());
    return fetch('http://example.com/todos')
      .then(res => res.json())
      .then(json => dispatch(addTodosSuccess(json.body)))
      .catch(ex => dispatch(addTodosFailure(ex)));
  };
}

can be tested like:

import expect from 'expect';
import { applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import * as actions from '../../actions/counter';
import * as types from '../../constants/ActionTypes';
import nock from 'nock';

const middlewares = [thunk];

/**
 * Creates a mock of Redux store with middleware.
 */
function mockStore(getState, expectedActions, onLastAction) {
  if (!Array.isArray(expectedActions)) {
    throw new Error('expectedActions should be an array of expected actions.');
  }
  if (typeof onLastAction !== 'undefined' && typeof onLastAction !== 'function') {
    throw new Error('onLastAction should either be undefined or function.');
  }

  function mockStoreWithoutMiddleware() {
    return {
      getState() {
        return typeof getState === 'function' ?
          getState() :
          getState;
      },

      dispatch(action) {
        const expectedAction = expectedActions.shift();
        expect(action).toEqual(expectedAction);
        if (onLastAction && !expectedActions.length) {
          onLastAction();
        }
        return action;
      }
    }
  }

  const mockStoreWithMiddleware = applyMiddleware(
    ...middlewares
  )(mockStoreWithoutMiddleware);

  return mockStoreWithMiddleware();
}

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll();
  });

  it('creates FETCH_TODO_SUCCESS when fetching todos has been done', (done) => {
    nock('http://example.com/')
      .get('/todos')
      .reply(200, { todos: ['do something'] });

    const expectedActions = [
      { type: types.FETCH_TODO_REQUEST },
      { type: types.FETCH_TODO_SUCCESS, body: { todos: ['do something']  } }
    ]
    const store = mockStore({ todos: [] }, expectedActions, done);
    store.dispatch(actions.fetchTodos());
  });
});
like image 93
Dan Abramov Avatar answered Nov 18 '22 08:11

Dan Abramov


Turns out, I don't need to mock any store methods or anything. Its as simple as mocking the ajax request. I am using superagent, so I did it something like this

const mockResponse = {
    body: {
        data: 'something'
    }
};

spyOn(superagent.Request.prototype, 'end').and.callFake((cb) => {
    cb(null, mockResponse); // callback with mocked response
});

// and expect it to be called
expect(superagent.Request.prototype.end).toHaveBeenCalled();
like image 2
Salman Avatar answered Nov 18 '22 09:11

Salman