Sub topic 16
Testing slices, selectors and connected components
This chapter assumes you can write a slice with createSlice, build a store with configureStore, and write selectors with createSelector. It also assumes basic experience with a test runner (Vitest or Jest) and React Testing Library. The examples use Vitest. In Jest, drop the vitest imports and use jest.fn() instead of vi.fn().
Test behavior at the right level
Redux Toolkit code splits into pieces with different testing costs. Test each piece at the cheapest level that still checks the behavior you care about.
| Piece | What to assert | How to test it |
|---|---|---|
| Slice reducer | New state for a given state and action | Call the reducer as a plain function |
| Selector | Returned value and memoization | Call it with a hand-built state object |
| Async thunk | Lifecycle actions and resulting state | Dispatch to a real store with `fetch` mocked |
| Connected component | What the user sees and does | Render inside a `Provider` with a real store |
Prefer real reducers and real stores to mocks. Reducers are pure and fast, so a mock buys you nothing and hides integration mistakes.
Testing a slice
A reducer is a function from (state, action) to a new state, so you can test it without a store. For the examples below, add export default counterSlice.reducer to the counter slice.
import { describe, it, expect } from 'vitest'
import reducer, { incremented, amountAdded } from './counterSlice'
describe('counter reducer', () => {
it('returns the initial state', () => {
expect(reducer(undefined, { type: 'unknown' })).toEqual({ value: 0 })
})
it('increments by one', () => {
expect(reducer({ value: 1 }, incremented())).toEqual({ value: 2 })
})
it('adds the payload amount', () => {
expect(reducer({ value: 1 }, amountAdded(5))).toEqual({ value: 6 })
})
it('does not mutate the previous state', () => {
const previous = Object.freeze({ value: 1 })
const next = reducer(previous, incremented())
expect(next).not.toBe(previous)
expect(previous.value).toBe(1)
})
})Passing undefined as the state makes Redux use initialState. The frozen-object test shows that Immer produced a new object instead of changing the old one. A reducer that returned a new value for a frozen input without throwing has handled the input immutably.
Slices with extraReducers
You can test extraReducers without any network code. The action creators on a thunk (pending, fulfilled, rejected) are ordinary action creators, so call them directly:
import { describe, it, expect } from 'vitest'
import todosReducer, { fetchTodos } from './todosSlice'
const initial = { items: [], status: 'idle', error: null }
describe('todos reducer', () => {
it('marks loading on pending', () => {
const state = todosReducer(initial, fetchTodos.pending('req-1'))
expect(state.status).toBe('loading')
})
it('stores items on fulfilled', () => {
const todos = [{ id: 1, title: 'Write tests', completed: false }]
const state = todosReducer(initial, fetchTodos.fulfilled(todos, 'req-1'))
expect(state.status).toBe('succeeded')
expect(state.items).toEqual(todos)
})
it('stores the message on rejected', () => {
const state = todosReducer(
initial,
fetchTodos.rejected(new Error('Request failed'), 'req-1')
)
expect(state.status).toBe('failed')
expect(state.error).toBe('Request failed')
})
})The second argument, 'req-1', is the request id that thunk actions carry. Any string works in a test.
Testing selectors
A selector is a function of state, so build the smallest state object it reads. Using the selectVisibleTodos selector from the selectors chapter (exported there):
import { describe, it, expect } from 'vitest'
import { selectVisibleTodos } from './todosSelectors'
const items = [
{ id: 1, title: 'A', completed: true },
{ id: 2, title: 'B', completed: false },
]
describe('selectVisibleTodos', () => {
it('returns only completed todos for the done filter', () => {
const state = { todos: { items, filter: 'done' } }
expect(selectVisibleTodos(state)).toEqual([items[0]])
})
it('returns every todo for other filters', () => {
const state = { todos: { items, filter: 'all' } }
expect(selectVisibleTodos(state)).toBe(items)
})
it('returns the same reference when inputs are unchanged', () => {
const first = selectVisibleTodos({ todos: { items, filter: 'done' } })
const second = selectVisibleTodos({ todos: { items, filter: 'done' } })
expect(second).toBe(first)
})
})The last test is the one that matters for createSelector. The two state objects are different, but items and filter are the same values, so the memoized selector returns the cached array. Use toBe for this check, because toEqual passes even when the selector recomputes and returns a new array every time. A selector that loses its memoization still gives correct results but causes extra renders.
You can also count recomputations. A createSelector result has recomputations() and resetRecomputations() methods. Reset the count in a beforeEach if you assert on it.
Testing connected components
Do not mock useSelector or useDispatch. A mocked hook lets a test pass while the real wiring is broken: the wrong state path, the wrong action, or a missing reducer. Render the component inside a real Provider instead, with a fresh store for each test.
Create a helper that accepts preloadedState and returns the store, so tests can both set up state and inspect it afterwards:
// test-utils.jsx
import { render } from '@testing-library/react'
import { Provider } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
export function renderWithProviders(
ui,
{
preloadedState,
store = configureStore({
reducer: { counter: counterReducer },
preloadedState,
}),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return <Provider store={store}>{children}</Provider>
}
return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }
}Now test the Counter component. Export it from its file with export function Counter(). The test uses toBeInTheDocument, which comes from @testing-library/jest-dom. Import @testing-library/jest-dom/vitest once in your setup file.
import { describe, it, expect } from 'vitest'
import { screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { renderWithProviders } from './test-utils'
import { Counter } from './Counter'
describe('Counter', () => {
it('shows the preloaded value', () => {
renderWithProviders(<Counter />, {
preloadedState: { counter: { value: 10 } },
})
expect(screen.getByText('10')).toBeInTheDocument()
})
it('updates the UI and the store when +5 is clicked', async () => {
const user = userEvent.setup()
const { store } = renderWithProviders(<Counter />, {
preloadedState: { counter: { value: 10 } },
})
await user.click(screen.getByRole('button', { name: '+5' }))
expect(screen.getByText('15')).toBeInTheDocument()
expect(store.getState().counter.value).toBe(15)
})
})The test checks the rendered output first, since that is what a user sees. It checks the store second, as a confirmation that the action reached the right slice.
Testing async thunks
Dispatch the thunk to a real store and check the final state. dispatch on a thunk returns a promise that resolves to the final fulfilled or rejected action. It does not throw on failure, so awaiting it is safe in both success and error tests.
import { describe, it, expect, vi, afterEach } from 'vitest'
import { configureStore } from '@reduxjs/toolkit'
import todosReducer, { fetchTodos } from './todosSlice'
function makeStore() {
return configureStore({ reducer: { todos: todosReducer } })
}
afterEach(() => {
vi.unstubAllGlobals()
})
describe('fetchTodos', () => {
it('stores todos on success', async () => {
const todos = [{ id: 1, title: 'A', completed: false }]
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: true, json: async () => todos })
)
const store = makeStore()
await store.dispatch(fetchTodos())
expect(store.getState().todos.status).toBe('succeeded')
expect(store.getState().todos.items).toEqual(todos)
})
it('records the error when the response is not ok', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }))
const store = makeStore()
await store.dispatch(fetchTodos())
expect(store.getState().todos.status).toBe('failed')
expect(store.getState().todos.error).toBe('Request failed')
})
})RTK Query endpoints
For components that use RTK Query hooks, intercept requests at the network level with Mock Service Worker (MSW) instead of mocking hooks. Two gotchas come up often:
- Relative URLs.
baseUrl: '/api'has no host in a Node test environment, andfetchrejects it. Use an absolute URL in tests, or set one in your test setup. - Cache leaks. The API slice caches results in the store. Add the
apireducer and middleware to your test store, and dispatchapi.util.resetApiState()inafterEachif you reuse a store.
Common failures
| Symptom | Likely cause |
|---|---|
| `could not find react-redux context value` | The component was rendered without a `Provider` |
| Test passes alone but fails in the full run | A shared singleton store keeps state between tests |
| `undefined` state in a component | The test store is missing the reducer the component reads |
| Selector test passes but the app re-renders too often | The test used `toEqual`, which hides lost memoization |
| Thunk test hangs or errors on URL parsing | `fetch` is not mocked, or the URL is relative |
Exercise
Why does the renderWithProviders helper create a new store for each call, and what two things does it give a test that a shared store would not?
Show answer
A new store per test keeps state from leaking between tests, so results do not depend on test order. It also lets each test set its own starting state through preloadedState, and it returns the store so the test can assert on store.getState() after interacting with the component.
Exercise
Write a reducer test, using the counterSlice from this chapter, that checks amountAdded(-3) applied to { value: 3 } gives { value: 0 }, and explain why toBe is the better matcher than toEqual for checking that a createSelector result is memoized.
Show answer
expect(reducer({ value: 3 }, amountAdded(-3))).toEqual({ value: 0 }). toBe checks reference identity, so it fails when the selector recomputes and returns a new array. toEqual compares contents and passes either way, so it cannot detect lost memoization.