Sub topic 16
Testing and resetting stores
This chapter assumes you can write a Zustand store with create, call getState and setState outside React, and run tests with Vitest or a similar runner. If those are new, review the chapters on creating stores and on using a store outside React first.
Why stores leak between tests
A store made with create lives at module level. Node loads a module once per test file, so every test in that file shares the same store object. If one test increments a counter, the next test starts with that incremented value.
This causes order-dependent failures. A test passes alone and fails in a full run, or the reverse.
Test the store without React
Actions are plain functions on the state, so you can call them directly. You don't need to render a component to test store logic.
import { beforeEach, expect, test } from 'vitest'
import { useCounterStore } from './counterStore'
const initialState = useCounterStore.getState()
beforeEach(() => {
useCounterStore.setState(initialState, true)
})
test('increment adds one', () => {
useCounterStore.getState().increment()
expect(useCounterStore.getState().count).toBe(1)
})The code works in three steps:
initialStateis captured once, when the test file loads, before any test changes the store.beforeEachcallssetState(initialState, true)before every test.- The test calls an action and reads the result with
getState().
Why the second argument matters
By default, setState merges the object you pass into the current state. The second argument, true, tells it to replace the state instead.
For a reset, replacing is the safer choice. The saved initialState object contains the actions as well as the data. Replacing the state puts back exactly what the store held at the start. A merge would also work for flat state, but it can leave behind keys that a test added.
Testing async actions
Async actions can be awaited. Stub fetch so the test doesn't call a real server. This example uses the useUsersStore from the async actions chapter.
import { beforeEach, expect, test, vi } from 'vitest'
import { useUsersStore } from './usersStore'
const initialState = useUsersStore.getState()
beforeEach(() => {
useUsersStore.setState(initialState, true)
vi.unstubAllGlobals()
})
test('fetchUsers stores the users', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
json: async () => [{ id: 1, name: 'Ada' }],
}),
)
await useUsersStore.getState().fetchUsers()
const state = useUsersStore.getState()
expect(state.users).toEqual([{ id: 1, name: 'Ada' }])
expect(state.loading).toBe(false)
expect(state.error).toBeNull()
})Common errors
- Forgetting the reset. Tests pass individually and fail together. Add the
beforeEachreset to each file that touches a store. - Capturing the initial state too late. If you call
getState()inside a test, or after another test has run, you save changed data as the "initial" state. Capture it at the top of the file. - Resetting without
true. A merge-style reset can leave extra keys in place. - Persisted stores. A store that uses
persistalso writes tolocalStorage. Clear it inbeforeEach, for example withlocalStorage.clear(), or the saved data can load into later tests. - Per-tree stores. If you use the context pattern, each provider creates its own store. Rendering a fresh provider in each test already gives you isolation, so no reset is needed.
Exercise
A test file has const initialState = useCounterStore.getState() at the top. The beforeEach hook calls useCounterStore.setState({ count: 0 }) with no second argument. The store also has fields added during other tests. Why is setState(initialState, true) a more reliable reset?
Show answer
setState({ count: 0 }) merges, so it only resets count and leaves any other fields the tests changed or added. setState(initialState, true) replaces the whole state with the saved snapshot, including the actions, so the store returns to exactly what it held when the file loaded.