How to unit test async Redux actions to mock ajax response

Salman

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?

Dan Abramov

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());
  });
});

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to unit test/stub async call in redux

From Dev

How do we mock fetch for Redux Async Actions?

From Dev

How to Test Redux Thunk Async Action with Jest Mock Module

From Dev

Unit test with redux-mock-store - How can I make this unit test pass?

From Dev

How to mock springSecurityService in an unit test

From Dev

How to mock this unit test in Python?

From Dev

How to android unit test and mock a static method

From Dev

how to mock $window to unit test AngularJS service?

From Dev

How to mock AngularFire 2 service in unit test?

From Dev

How to mock the UserAgent property for an HttpRequest in a unit test?

From Dev

How to unit test this function without mock asserts?

From Dev

How to mock browserHistory in unit test environment?

From Dev

How to mock multiple components in camel unit test?

From Dev

How to mock an Akka Actor to Unit Test a class?

From Dev

How to mock a generic parameter for a unit test in Java?

From Dev

How to mock a FormBuilder for Angular Component Unit Test

From Dev

How to mock multiple components in camel unit test?

From Dev

How to mock the UserAgent property for an HttpRequest in a unit test?

From Dev

How to mock AngularFire 2 service in unit test?

From Dev

How to define Mock Cursor for Android Unit Test

From Dev

Async actions in Redux

From Dev

Mock IMemoryCache in unit test

From Dev

How to unit test RelayCommand that Executes an async method?

From Dev

How to Unit test ViewModel with async initialization in WPF

From Dev

How to unit test a method with HttpWebRequest/Response dependencies

From Dev

how to write async redux actions in a non-fake app

From Dev

React Redux how to dispatch async actions and update state

From Dev

Redux connect chaining async actions

From Dev

How to make a unit test for ajax calls

Related Related

  1. 1

    How to unit test/stub async call in redux

  2. 2

    How do we mock fetch for Redux Async Actions?

  3. 3

    How to Test Redux Thunk Async Action with Jest Mock Module

  4. 4

    Unit test with redux-mock-store - How can I make this unit test pass?

  5. 5

    How to mock springSecurityService in an unit test

  6. 6

    How to mock this unit test in Python?

  7. 7

    How to android unit test and mock a static method

  8. 8

    how to mock $window to unit test AngularJS service?

  9. 9

    How to mock AngularFire 2 service in unit test?

  10. 10

    How to mock the UserAgent property for an HttpRequest in a unit test?

  11. 11

    How to unit test this function without mock asserts?

  12. 12

    How to mock browserHistory in unit test environment?

  13. 13

    How to mock multiple components in camel unit test?

  14. 14

    How to mock an Akka Actor to Unit Test a class?

  15. 15

    How to mock a generic parameter for a unit test in Java?

  16. 16

    How to mock a FormBuilder for Angular Component Unit Test

  17. 17

    How to mock multiple components in camel unit test?

  18. 18

    How to mock the UserAgent property for an HttpRequest in a unit test?

  19. 19

    How to mock AngularFire 2 service in unit test?

  20. 20

    How to define Mock Cursor for Android Unit Test

  21. 21

    Async actions in Redux

  22. 22

    Mock IMemoryCache in unit test

  23. 23

    How to unit test RelayCommand that Executes an async method?

  24. 24

    How to Unit test ViewModel with async initialization in WPF

  25. 25

    How to unit test a method with HttpWebRequest/Response dependencies

  26. 26

    how to write async redux actions in a non-fake app

  27. 27

    React Redux how to dispatch async actions and update state

  28. 28

    Redux connect chaining async actions

  29. 29

    How to make a unit test for ajax calls

HotTag

Archive