Member-only story
Mastering Jest: Day 6 — Testing Redux with Jest
Introduction
Welcome to Day 6 of our Jest journey! Yesterday, we explored the power of snapshot testing. Today, we’ll focus on testing Redux, a popular state management library, with Jest. Testing Redux ensures that your state management logic is robust and behaves as expected.
Setting Up Redux for Testing
To get started, let’s create a simple Redux setup:
// actions.js
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
// reducer.js
const initialState = { count: 0 };
export default function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
Testing Actions
Actions are simple objects that describe changes. Here’s how to test them:
// actions.test.js
import { increment, decrement } from './actions';
test('increment action', () => {
expect(increment()).toEqual({ type: 'INCREMENT' });
});
test('decrement action', () => {
expect(decrement()).toEqual({ type: 'DECREMENT' });
});