Prevent hook state from leaking between tests
React component tests
Zustand · Const
The testing guide shows how to mock Zustand's creators and reset every store to its initial state after each test. The pattern supports both React-bound and standalone stores.
The testing guide recommends mocking Zustand's store creators, capturing each store's initial state, and registering a reset function that replaces the current state with that snapshot. An afterEach hook then invokes all registered resets inside act, isolating tests while supporting both React-bound and standalone stores.
afterEach(() => {
act(() => {
storeResetFns.forEach((resetFn) => resetFn())
})
})import { act } from '@testing-library/react'
import { storeResetFns } from './__mocks__/zustand'
afterEach(() => {
act(() => {
storeResetFns.forEach((reset) => reset())
})
})After each test, run every registered reset function inside React's act helper so stores return to their initial state.
React component tests
Store unit tests
Mixed Zustand applications
The mock wraps Zustand's creators, records each store's initial state, and adds a reset callback to a shared set. The test lifecycle invokes those callbacks after every test inside act.
Follow-up: Why capture getInitialState instead of reading state during cleanup? The initial snapshot represents the store's baseline, while cleanup state may already contain mutations from the test.
The guide handles both create and createStore because Zustand exposes React-bound and vanilla store creators. The mock preserves the actual exports while replacing the creation functions with reset-aware wrappers.
Follow-up: What broader design concern does this address? Tests may use either hook-based stores or standalone stores, so resetting only one creator leaves coverage gaps.
The reset callback calls setState with the saved initial state and the replace flag enabled. That replaces the complete store state instead of shallowly merging the snapshot with leftovers.
Follow-up: When would replacement be especially valuable? It prevents keys introduced or retained during a test from surviving cleanup.
createcreateStoregetInitialStatesetStateactJestVitest