Testing Action Creators

Learn how to test the actions in the Redux lifecycle.

We'll cover the following

We have tried to keep asynchronous flows out of action creators throughout this course by moving them into middleware and utility functions. This approach allows for easy testing of action creators, as they are functions that return plain JavaScript objects:

import * as actions from 'constants/actionTypes';

export const setRecipes = recipes => ({
 type: actions.SET_RECIPES,
 payload: recipes
});

Our setRecipes() action creator receives a single parameter and returns a plain JavaScript object. Since there is no control flow logic or side effects, any call to this function will always return the same value, making it very easy to test:

import * as actions from 'actions'

describe('actions/recipes', () => {
 it('addRecipe', () => {
   const expected = { type: 'ADD_RECIPE', payload: 'test' };
   const actual = actions.addRecipe('test');

   expect(actual).toEqual(expected);
 });
});

This test is built into three parts. First, we calculate what our action creator should return when called with 'test' as an argument—in this case, a JavaScript object containing two keys, type and payload:

const expected = { type: 'ADD_RECIPE', payload: 'test' };

The second stage is running the action creator actions.addRecipe('test') to get the value built by our action creator’s implementation:

const actual = actions.addRecipe('test');

And the final stage is using Jest’s expect() and toEqual() functions to verify that the actual and expected results are the same:

expect(actual).toEqual(expected);

If the expected and actual objects differ, Jest will throw an error and provide information describing the differences, allowing us to catch incorrect implementations.

Improving the code

Due to the simplicity of this code, it is common to combine multiple stages into a single call and rewrite the test as follows:

it('ADD_RECIPE', () => {
  const expected = { type: 'ADD_RECIPE', payload: 'test' };

  expect(actions.addRecipe('test')).toEqual(expected);
});

Get hands-on with 1400+ tech skills courses.