Dynamic Action Creators

Let's learn how to create dynamic action creators.

In some cases, action creators might contain logic that emits different actions based on the input parameters. As long as no asynchronous code or other external entities like localStorage are touched, we can easily test the logic by providing different input parameters to the action creator and verifying that it creates the correct object every time:

// An action creator that modifies the input
export const addRecipe = (title) => ({
  type: actions.ADD_RECIPE,
  payload: title || "Default"
});

The modified addRecipe() action creator will set the payload to "Default" if the user does not provide a title. To test this behavior, we can create two tests, one that provides a parameter (as we already did) and one that provides an empty string. A fully comprehensive test might contain multiple “empty string” cases, for null, undefined, and '':

// Combined test of multiple falsy input values
it('ADD_RECIPE', () => {
  expect(actions.addRecipe(undefined)).toMatchSnapshot();
  expect(actions.addRecipe(null)).toMatchSnapshot();
  expect(actions.addRecipe('')).toMatchSnapshot();
});

In contrast to what we discussed earlier, here, we tried putting multiple expect() functions into the same test. While this approach will work, it will be harder to identify which of the test cases failed in the event of an error.

Since we use JavaScript to write our tests, we can easily create test cases for each input value without increasing our code size significantly (by creating an it() clause for each). We can do that by adding all the possible inputs into an array and automatically creating corresponding it() blocks:

// Automatically creating tests for each test case
[undefined, null, ''].forEach((param) =>
  it(`ADD_RECIPE with ${param}` , () => {
    expect(actions.addRecipe(param)).toMatchSnapshot()
  }));

Using this approach, we get three different it() blocks automatically generated by JavaScript, keeping our tests clear and the code short.

Get hands-on with 1200+ tech skills courses.