|
| 1 | +// Copied from https://zustand.docs.pmnd.rs/guides/testing#jest |
| 2 | +// __mocks__/zustand.ts |
| 3 | +import * as zustand from "zustand"; |
| 4 | +import { act } from "@testing-library/react"; |
| 5 | + |
| 6 | +const { create: actualCreate, createStore: actualCreateStore } = |
| 7 | + jest.requireActual<typeof zustand>("zustand"); |
| 8 | + |
| 9 | +// a variable to hold reset functions for all stores declared in the app |
| 10 | +export const storeResetFns = new Set<() => void>(); |
| 11 | + |
| 12 | +const createUncurried = <T>(stateCreator: zustand.StateCreator<T>) => { |
| 13 | + const store = actualCreate(stateCreator); |
| 14 | + const initialState = store.getInitialState(); |
| 15 | + storeResetFns.add(() => { |
| 16 | + store.setState(initialState, true); |
| 17 | + }); |
| 18 | + return store; |
| 19 | +}; |
| 20 | + |
| 21 | +// when creating a store, we get its initial state, create a reset function and add it in the set |
| 22 | +export const create = (<T>(stateCreator: zustand.StateCreator<T>) => { |
| 23 | + console.log("zustand create mock"); |
| 24 | + |
| 25 | + // to support curried version of create |
| 26 | + return typeof stateCreator === "function" |
| 27 | + ? createUncurried(stateCreator) |
| 28 | + : createUncurried; |
| 29 | +}) as typeof zustand.create; |
| 30 | + |
| 31 | +const createStoreUncurried = <T>(stateCreator: zustand.StateCreator<T>) => { |
| 32 | + const store = actualCreateStore(stateCreator); |
| 33 | + const initialState = store.getInitialState(); |
| 34 | + storeResetFns.add(() => { |
| 35 | + store.setState(initialState, true); |
| 36 | + }); |
| 37 | + return store; |
| 38 | +}; |
| 39 | + |
| 40 | +// when creating a store, we get its initial state, create a reset function and add it in the set |
| 41 | +export const createStore = (<T>(stateCreator: zustand.StateCreator<T>) => { |
| 42 | + console.log("zustand createStore mock"); |
| 43 | + |
| 44 | + // to support curried version of createStore |
| 45 | + return typeof stateCreator === "function" |
| 46 | + ? createStoreUncurried(stateCreator) |
| 47 | + : createStoreUncurried; |
| 48 | +}) as typeof zustand.createStore; |
| 49 | + |
| 50 | +// reset all stores after each test run |
| 51 | +afterEach(() => { |
| 52 | + act(() => { |
| 53 | + storeResetFns.forEach((resetFn) => { |
| 54 | + resetFn(); |
| 55 | + }); |
| 56 | + }); |
| 57 | +}); |
0 commit comments