Blog>
Snippets

Unit Testing createReducer with Multi-Model Form Logic

Present a test case using Jest that verifies the behavior of a reducer created with createReducer for a form with multiple data models.
import { createReducer } from '@reduxjs/toolkit';
import { editStart, editStop, updateModel } from './actions';

// Define the initial state for the multi-model form
const initialState = {
  isEditing: false,
  models: {}
};

// Create the reducer using the initialState and a map of action handlers
const formReducer = createReducer(initialState, {
  [editStart]: (state, action) => {
    state.isEditing = true;
    state.models[action.payload.modelType] = action.payload.data;
  },
  [editStop]: (state) => {
    state.isEditing = false;
  },
  [updateModel]: (state, action) => {
    const { modelType, data } = action.payload;
    state.models[modelType] = { ...state.models[modelType], ...data };
  }
});

export default formReducer;
Defines an initial state and uses createReducer from Redux Toolkit to handle actions for starting editing, stopping editing, and updating model data within a form.
import { editStart, editStop, updateModel } from './actions';
import formReducer from './formReducer';

describe('formReducer', () => {
  it('should handle editStart action', () => {
    const startAction = editStart({ modelType: 'user', data: { name: 'John' } });
    const newState = formReducer(undefined, startAction);
    expect(newState).toEqual({ isEditing: true, models: { user: { name: 'John' } } });
  });

  it('should handle editStop action', () => {
    const stopAction = editStop();
    const initialState = { isEditing: true, models: { user: { name: 'John' } } };
    const newState = formReducer(initialState, stopAction);
    expect(newState).toEqual({ isEditing: false, models: { user: { name: 'John' } } });
  });

  it('should handle updateModel action', () => {
    const updateAction = updateModel({ modelType: 'user', data: { email: 'john@example.com' } });
    const initialState = { isEditing: true, models: { user: { name: 'John' } } };
    const newState = formReducer(initialState, updateAction);
    expect(newState).toEqual({ isEditing: true, models: { user: { name: 'John', email: 'john@example.com' } } });
  });
});
Conducts unit tests using Jest for the formReducer that is built using createReducer to ensure that it handles editStart, editStop, and updateModel actions correctly.