Sub topic 16
Testing and resetting stores
A Zustand store created with create lives at module level. That makes it easy to import, but it also means state carries over from one test to the next. This chapter shows how to reset a store between tests, test actions with and without React, and handle async actions and persist.
It assumes you have read the earlier chapters on create, set, async actions, and persist. It also assumes you know Vitest basics (test, expect, beforeEach). The examples use Vitest. The same ideas work in Jest with jest.fn in place of vi.fn.
Why stores leak state between tests
Module-level state means every test in a file imports the same store instance. If one test calls increment(), the next test starts with count at 1. The failure depends on test order, which makes it hard to trace.
Vitest gives each test file its own module registry by default, so stores do not leak between files. They do leak between tests inside one file. Resetting is therefore a per-file concern.
Resetting with setState and the replace flag
The pattern is to take a snapshot once, then restore it before every test:
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)
})
test('starts again at zero', () => {
expect(useCounterStore.getState().count).toBe(0)
})The second argument, true, tells setState to replace the state instead of merging into it. The snapshot is the full state object, including the action functions, so replacing is safe. Without true, any key that a test added would survive the reset.
Recent Zustand versions also provide getInitialState(), which returns the state the store was created with. This is a more robust snapshot source, because it does not depend on when your test file first reads the store:
beforeEach(() => {
useCounterStore.setState(useCounterStore.getInitialState(), true)
})Use getInitialState() when your version has it. Otherwise capture getState() at module load, before any test runs.
Testing actions without React
Because getState() returns the current state, including actions, you can test store logic with no component and no renderer:
import { beforeEach, expect, test } from 'vitest'
import { useCounterStore } from './counterStore'
beforeEach(() => {
useCounterStore.setState(useCounterStore.getInitialState(), true)
})
test('reset returns count to zero', () => {
useCounterStore.setState({ count: 5 })
useCounterStore.getState().reset()
expect(useCounterStore.getState().count).toBe(0)
})Call getState() again after each action. Destructuring count before the action gives you the old value, because state objects are replaced, not mutated.
Seeding state with setState before the action keeps each test focused on one behavior, instead of calling increment() five times to reach a starting point.
Testing async actions
The fetchUsers action calls fetch, so stub it. Awaiting the action works because it returns a promise.
import { afterEach, beforeEach, expect, test, vi } from 'vitest'
import { useUsersStore } from './usersStore'
beforeEach(() => {
useUsersStore.setState(useUsersStore.getInitialState(), true)
})
afterEach(() => {
vi.unstubAllGlobals()
})
test('fetchUsers stores the users', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({
ok: true,
status: 200,
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()
})
test('fetchUsers records a failed request', async () => {
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue({ ok: false, status: 500, json: async () => [] }),
)
await useUsersStore.getState().fetchUsers()
const state = useUsersStore.getState()
expect(state.error).toBe('Request failed: 500')
expect(state.loading).toBe(false)
expect(state.users).toEqual([])
})Both tests check that loading ends as false. A common bug is forgetting to clear it on one of the two paths.
Testing components that read a store
Component tests need a DOM, so mark the file for jsdom. First, a small component file:
import { useCounterStore } from './counterStore'
export function Counter() {
const count = useCounterStore((state) => state.count)
const increment = useCounterStore((state) => state.increment)
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Add one</button>
</div>
)
}Then the test:
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, expect, test } from 'vitest'
import { Counter } from './Counter'
import { useCounterStore } from './counterStore'
beforeEach(() => {
useCounterStore.setState(useCounterStore.getInitialState(), true)
})
afterEach(() => {
cleanup()
})
test('clicking the button updates the count', () => {
render(<Counter />)
fireEvent.click(screen.getByText('Add one'))
expect(screen.getByText('Count: 1')).toBeTruthy()
})
test('renders state that was seeded before mounting', () => {
useCounterStore.setState({ count: 41 })
render(<Counter />)
expect(screen.getByText('Count: 41')).toBeTruthy()
})
test('re-renders when the store changes from outside', () => {
render(<Counter />)
act(() => {
useCounterStore.setState({ count: 7 })
})
expect(screen.getByText('Count: 7')).toBeTruthy()
})Without Vitest's globals option, React Testing Library does not clean up automatically, so the example calls cleanup() itself. Wrap any store update that happens while a component is mounted in act. Otherwise React warns that an update was not wrapped.
Testing persisted stores
A store using persist also writes to localStorage. In jsdom that storage is shared across tests in a file, so clear it as part of the reset. Using the cart store from the middleware chapter:
// @vitest-environment jsdom
import { beforeEach, expect, test } from 'vitest'
import { useCartStore } from './cartStore'
beforeEach(() => {
useCartStore.setState(useCartStore.getInitialState(), true)
localStorage.clear()
})
test('persists only the items field', () => {
useCartStore.getState().addItem('apple')
useCartStore.getState().toggleOpen()
const saved = JSON.parse(localStorage.getItem('cart-storage') ?? '{}')
expect(saved.state).toEqual({ items: ['apple'] })
})Order matters in beforeEach. Calling setState triggers a write, so clear storage after it. The second assertion, that isOpen is absent from saved.state, confirms partialize works.
To test hydration, write a value into localStorage and then call useCartStore.persist.rehydrate(). The persist middleware adds a persist property to the store with this method and others such as clearStorage().
Stores created per tree
The vanilla createStore pattern needs no reset. Each test builds a new store, so nothing is shared. Export the factory from the module to test it directly:
import { expect, test } from 'vitest'
import { createStore } from 'zustand'
interface CounterState {
count: number
increment: () => void
}
const createCounterStore = (initialCount: number) =>
createStore<CounterState>()((set) => ({
count: initialCount,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
test('each store starts from its own initial count', () => {
const a = createCounterStore(5)
const b = createCounterStore(0)
a.getState().increment()
expect(a.getState().count).toBe(6)
expect(b.getState().count).toBe(0)
})This is a strong reason to prefer the factory-plus-context approach when your tests or server rendering need isolation.
Automatic resets with a mock
If you have many stores, repeating beforeEach in every file is tedious. The Zustand documentation describes a __mocks__/zustand module that wraps create, records each store's initial state, and resets all stores in an afterEach hook. It removes the boilerplate, but it hides behavior in a mock. For a handful of stores, an explicit beforeEach is easier to read and debug.
Gotchas
- Mutated snapshots. The snapshot only stays clean if state is updated immutably. If a test or action mutates a nested object in place, the snapshot shares that object and the reset restores the dirty value. Immer-based stores are safe because Immer copies on write.
- Concurrent tests.
test.concurrentruns tests in the same file at the same time against one store. A sharedbeforeEachreset cannot isolate them. Run store tests sequentially or create a store per test. - Leftover subscriptions. Replacing state notifies subscribers. Call the function returned by
subscribeat the end of a test that registers a listener. - Late snapshots. A snapshot taken inside a test, or after another test changed state, is not the initial state. Capture it at module load or use
getInitialState().
Exercise
A test file captures const initialState = useTodoStore.getState() and resets with setState(initialState, true). One test runs useTodoStore.getState().todos[0].done = true to set up its data. Later tests still see done as true after the reset. Why, and how do you fix it?
Show answer
The direct assignment mutates the todo object in place. The snapshot's todos array points to the same object, so the snapshot is changed too and the reset restores the dirty value. Fix it by seeding state immutably with setState({ todos: [{ id: 1, title: 'Write tutorial', done: true }] }), or by using getInitialState() with an immer-based store so updates copy on write.
Exercise
Why does the persist test call localStorage.clear() after setState(initialState, true) and not before it?
Show answer
Replacing the state triggers the persist middleware to write the new state to localStorage. Clearing first would leave that fresh write in storage for the next test. Clearing afterward leaves storage empty.