Blog>
Snippets

Testing Redux Action Creators and Reducers with Types

Outline how to test Redux action creators and reducers with explicitly declared action types, ensuring type correctness.
// Define Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

// Action Creators
function increment() {
  return { type: INCREMENT };
}

function decrement() {
  return { type: DECREMENT };
}

// Reducer with initial state
function counterReducer(state = { count: 0 }, action) {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case DECREMENT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

// Test cases
// 1. Test increment action
const incAction = increment();
console.assert(incAction.type === INCREMENT, 'increment action type should be INCREMENT');

// 2. Test decrement action
const decAction = decrement();
console.assert(decAction.type === DECREMENT, 'decrement action type should be DECREMENT');

// 3. Test reducer's response to increment action
const incState = counterReducer(undefined, incAction);
console.assert(incState.count === 1, 'counterReducer should increment count');

// 4. Test reducer's response to decrement action
const decState = counterReducer(undefined, decAction);
console.assert(decState.count === -1, 'counterReducer should decrement count');
This code example outlines how to define action types, action creators, and a reducer in Redux. It also includes test cases for testing the action creators and the reducer. The `console.assert` statements ensure that the action creators return the correct action types, and that the reducer updates the state correctly in response to those actions.