import { jest } from '@jest/globals'; import { createStore, type StoreApi } from 'zustand'; export { subscribeTo } from './src/index'; // Needed for all mocks using stores const availableStores: Record = {}; const initialStates: Record = {}; interface StoreEntity { value: StoreApi; active: boolean; } export type MockedStore = StoreApi & { resetMock: () => void; }; export const mockStores = availableStores; export function createGlobalStore(name: string, initialState: T): StoreApi { // We ignore whether there's already a store with this name so that tests // don't have to worry about clearing old stores before re-creating them. const store = createStore()(() => initialState); initialStates[name] = initialState; availableStores[name] = { value: store, active: true, }; return instrumentedStore(name, store); } export function registerGlobalStore(name: string, store: StoreApi): StoreApi { availableStores[name] = { value: store, active: true, }; return instrumentedStore(name, store); } export function getGlobalStore(name: string, fallbackState?: T): StoreApi { const available = availableStores[name]; if (!available) { const store = createStore()(() => fallbackState ?? ({} as unknown as T)); initialStates[name] = fallbackState; availableStores[name] = { value: store, active: false, }; return instrumentedStore(name, store); } return instrumentedStore(name, available.value); } function instrumentedStore(name: string, store: StoreApi) { return { getInitialState: jest.spyOn(store, 'getInitialState'), getState: jest.spyOn(store, 'getState'), setState: jest.spyOn(store, 'setState'), subscribe: jest.spyOn(store, 'subscribe'), destroy: jest.spyOn(store, 'destroy'), resetMock: () => store.setState(initialStates[name]), } as unknown as MockedStore; }