Sub topic 16
Testing slices, selectors and connected components
This chapter assumes you know createSlice, configureStore, createSelector, and the React-Redux hooks from earlier chapters. It also assumes you have a test runner such as Vitest or Jest. The examples use Vitest and React Testing Library.
What to test
Redux Toolkit code splits into three parts, and each is tested differently.
| Part | What it is | How to test it |
|---|---|---|
| Reducer | A pure function of `(state, action)` | Call it directly and compare the result |
| Selector | A pure function of state | Call it with a hand-built state object |
| Connected component | A component using `useSelector` and `useDispatch` | Render it inside a `Provider` with a real store |
Pure functions need no mocking. Prefer a real store over a mocked one for components, because a real store tests the same wiring your app uses.
Testing a slice
A slice's reducer is a plain function. Pass it a state and an action created by the slice's action creators, then check the returned state.
import { describe, it, expect } from 'vitest'
import counterReducer, { incremented, amountAdded } from './counterSlice'
describe('counter reducer', () => {
it('returns the initial state', () => {
expect(counterReducer(undefined, { type: 'unknown' })).toEqual({ value: 0 })
})
it('handles incremented', () => {
expect(counterReducer({ value: 1 }, incremented())).toEqual({ value: 2 })
})
it('handles amountAdded', () => {
expect(counterReducer({ value: 1 }, amountAdded(5))).toEqual({ value: 6 })
})
})This assumes counterSlice.js also has export default counterSlice.reducer. Passing undefined as the state checks that the initial state is correct.
Testing a selector
Build the smallest state object the selector needs. For a createSelector selector, also check that it returns the same reference when the inputs have not changed.
import { describe, it, expect } from 'vitest'
import { selectVisibleTodos } from './todosSelectors'
const makeState = (filter) => ({
todos: {
filter,
items: [
{ id: 1, text: 'Write tests', completed: true },
{ id: 2, text: 'Ship it', completed: false },
],
},
})
describe('selectVisibleTodos', () => {
it('returns only completed todos for the done filter', () => {
const result = selectVisibleTodos(makeState('done'))
expect(result).toEqual([{ id: 1, text: 'Write tests', completed: true }])
})
it('returns the same reference when inputs are unchanged', () => {
const state = makeState('done')
expect(selectVisibleTodos(state)).toBe(selectVisibleTodos(state))
})
})Testing a connected component
Create a helper that renders a component with a fresh store. A fresh store per test stops state leaking between tests.
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Provider } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
import { describe, it, expect } from 'vitest'
import counterReducer from './counterSlice'
import { Counter } from './Counter'
function renderWithStore(ui, preloadedState) {
const store = configureStore({
reducer: { counter: counterReducer },
preloadedState,
})
render(<Provider store={store}>{ui}</Provider>)
return store
}
describe('Counter', () => {
it('shows the preloaded value', () => {
renderWithStore(<Counter />, { counter: { value: 7 } })
expect(screen.getByText('7')).toBeTruthy()
})
it('updates the store and the screen on click', async () => {
const store = renderWithStore(<Counter />)
await userEvent.click(screen.getByText('+5'))
expect(screen.getByText('5')).toBeTruthy()
expect(store.getState().counter.value).toBe(5)
})
})This assumes Counter is exported by name from Counter.jsx. The preloadedState option starts a test in any state you need, so you skip clicking through setup steps.
Common errors
- Sharing one store across tests. Create the store inside the helper, not at module level.
- Mocking
useSelector. This hides wiring bugs. Use a real store withpreloadedState. - Mutating the state you pass in. Reducers return new objects, so compare the return value, not the input.
- Forgetting
awaitonuserEvent. The assertion then runs before the update.
Exercise
A test for a connected component passes alone but fails when run with the other tests in the file. The store is created once at the top of the test file. What is the likely cause and the fix?
Show answer
The tests share one store, so state changed by an earlier test carries into later ones. Create a new store for each test, for example inside a renderWithStore helper, and set the starting state with preloadedState.