|
| 1 | +import { act } from '@testing-library/react'; |
| 2 | +import { afterEach, vi } from 'vitest'; |
| 3 | +import * as zustand from 'zustand'; |
| 4 | +import type { StateCreator, StoreApi, UseBoundStore } from 'zustand'; |
| 5 | + |
| 6 | +const { create: zCreate, createStore: zCreateStore } = await vi.importActual<typeof zustand>('zustand'); |
| 7 | + |
| 8 | +// a variable to hold reset functions for all stores declared in the app |
| 9 | +const STORE_RESET_FUNCTIONS = new Set<() => void>(); |
| 10 | + |
| 11 | +function createUncurried<T>(stateCreator: StateCreator<T>): UseBoundStore<StoreApi<T>> { |
| 12 | + const store = zCreate(stateCreator); |
| 13 | + const initialState = store.getInitialState(); |
| 14 | + STORE_RESET_FUNCTIONS.add(() => { |
| 15 | + store.setState(initialState, true); |
| 16 | + }); |
| 17 | + return store; |
| 18 | +} |
| 19 | + |
| 20 | +function createStoreUncurried<T>(stateCreator: StateCreator<T>): StoreApi<T> { |
| 21 | + const store = zCreateStore(stateCreator); |
| 22 | + const initialState = store.getInitialState(); |
| 23 | + STORE_RESET_FUNCTIONS.add(() => { |
| 24 | + store.setState(initialState, true); |
| 25 | + }); |
| 26 | + return store; |
| 27 | +} |
| 28 | + |
| 29 | +afterEach(() => { |
| 30 | + act(() => { |
| 31 | + STORE_RESET_FUNCTIONS.forEach((resetFn) => { |
| 32 | + resetFn(); |
| 33 | + }); |
| 34 | + }); |
| 35 | +}); |
| 36 | + |
| 37 | +export function create<T>(stateCreator: StateCreator<T>): UseBoundStore<StoreApi<T>> { |
| 38 | + if (typeof stateCreator === 'function') { |
| 39 | + return createUncurried(stateCreator); |
| 40 | + } |
| 41 | + return createUncurried as unknown as UseBoundStore<StoreApi<T>>; |
| 42 | +} |
| 43 | + |
| 44 | +export function createStore<T>(stateCreator: StateCreator<T>): StoreApi<T> { |
| 45 | + if (typeof stateCreator === 'function') { |
| 46 | + return createStoreUncurried(stateCreator); |
| 47 | + } |
| 48 | + return createStoreUncurried as unknown as StoreApi<T>; |
| 49 | +} |
0 commit comments