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() {

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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 {

function fetchTodosSuccess(body) {
  return {

function fetchTodosFailure(ex) {
  return {

export function fetchTodos(data) {
  return dispatch => {
    return fetch('')
      .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() :

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

  const mockStoreWithMiddleware = applyMiddleware(

  return mockStoreWithMiddleware();

describe('async actions', () => {
  afterEach(() => {

  it('creates FETCH_TODO_SUCCESS when fetching todos has been done', (done) => {
      .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);

Method 2

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

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x