Testing Action Creators

Learn how to test the action creators in Redux.

Because action creators are nothing more than plain JavaScript functions which require only constants and do not rely on state, they are very easy to test. Given the same input, they will always return the same output. Action creators also never modify any state directly but rather only return a new object. Thus, our tests can pass input values to action creators and verify that the correct object is returned for each case:

import { ADD_RECIPE } from 'constants/actionTypes';
import { addRecipe } from 'actions/recipes';

describe('actions/recipes', () => {
  it ('addRecipe', () => {
    const title = 'Omelette';
    const description = 'Fast and simple';
    const expectedAction = {
      type: ADD_RECIPE,
      title,
      description
    };

    expect(addRecipe(title, description)).to.equal(expectedAction);
  });

  it ('addRecipe with default title', () => {
    const description = 'Fast and simple';
    const expectedAction = {
      type: ADD_RECIPE,
      title: 'Untitled',
      description
    };

    expect(addRecipe(null, description)).to.equal(expectedAction);
  });
});

You must have jest installed. You can run the command by typing:

npm test

More complex action creators might use helper functions to build the action object. E.g, a SET_TITLE action uses function trimTitle(), removes whitespace from around a string. We would test the method separately from the action creator function itself, verifying that the action creator called that method and passed it the needed parameters.

Get hands-on with 1400+ tech skills courses.