Making the Tests Pretty

Write the code in a presentable way.

Now that we’ve solved all the functionality issues, we can use the same tricks we used in the action creator tests to simplify our reducer tests. Here are the original tests:

it('should add recipe to empty list', () => {
  const action = { type: ADD_RECIPE, payload: 'test' };
  const expected = [{ title: "test" }];

  expect(reducer(initialState, action)).toEqual(expected);
});

it('should add recipe to non-empty list', () => {
  const baseState = reducer(initialState,
    { type: ADD_RECIPE, payload: 'first' });
  const action   = { type: ADD_RECIPE, payload: 'test' };
  const expected = [{ title: "first" }, { title: "test" }];
  const actual   = reducer(baseState, action);

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

Step 1: Combine

The first step will be to combine action, actual, and expect() into a single line:

it('should add recipe to empty list', () => {
  const expected = [{ title: "test" }];

  expect(reducer(initialState, { type: ADD_RECIPE, payload: 'test' }))
    .toEqual(expected);
});

it('should add recipe to non-empty list', () => {
  const baseState = reducer(initialState, { type: ADD_RECIPE, payload: 'first' });
  const expected  = [{ title: "first" }, { title: "test" }];

  expect(reducer(baseState, { type: ADD_RECIPE, payload: 'test' }))
    .toEqual(expected);
});

Step 2: Implementing Jest snapshot

The second step is to use Jest’s snapshots instead of manually calculated expected values:

it('should add recipe to empty list', () => {
  expect(reducer(initialState,
    { type: ADD_RECIPE, payload: 'test' }))
    .toMatchSnapshot()
});

it('should add recipe to non-empty list', () => {
  const baseState = reducer(initialState,
    { type: ADD_RECIPE, payload: 'first' });

  expect(reducer(baseState, { type: ADD_RECIPE, payload: 'test' }))
    .toMatchSnapshot();
});

Get hands-on with 1200+ tech skills courses.