-
Notifications
You must be signed in to change notification settings - Fork 208
/
mock.ts
65 lines (52 loc) · 1.78 KB
/
mock.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import { createStore, type StoreApi } from 'zustand';
export { subscribeTo } from './src/index';
// Needed for all mocks using stores
const availableStores: Record<string, StoreEntity> = {};
const initialStates: Record<string, any> = {};
interface StoreEntity {
value: StoreApi<any>;
active: boolean;
}
export type MockedStore<T> = StoreApi<T> & {
resetMock: () => void;
};
export const mockStores = availableStores;
export function createGlobalStore<T>(name: string, initialState: T): StoreApi<T> {
// 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<T>()(() => initialState);
initialStates[name] = initialState;
availableStores[name] = {
value: store,
active: true,
};
return instrumentedStore(name, store);
}
export function registerGlobalStore<T>(name: string, store: StoreApi<T>): StoreApi<T> {
availableStores[name] = {
value: store,
active: true,
};
return instrumentedStore(name, store);
}
export function getGlobalStore<T>(name: string, fallbackState?: T): StoreApi<T> {
const available = availableStores[name];
if (!available) {
const store = createStore<T>()(() => 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<T>(name: string, store: StoreApi<T>) {
return {
getState: jest.spyOn(store, 'getState'),
setState: jest.spyOn(store, 'setState'),
subscribe: jest.spyOn(store, 'subscribe'),
resetMock: () => store.setState(initialStates[name]),
} as any as MockedStore<T>;
}