/
mock-use-effect.ts
37 lines (28 loc) · 1.17 KB
/
mock-use-effect.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
type UseEffectSignature = (fn: () => void, triggers?: unknown[]) => void;
type FunctionBody = string;
type CleanupFunction = () => void;
const noDepsOrDifferent = (previousDependencies: unknown[], currentDependencies: unknown[]): boolean => {
return previousDependencies === undefined ||
previousDependencies.some((prevDep, index) => prevDep !== currentDependencies[index]);
}
const mockUseEffect = (): UseEffectSignature => {
const previousCalls = new Map<FunctionBody, unknown[]>();
const cleanupFunctions = new Map<string, CleanupFunction>();
return (effect: () => CleanupFunction | void, dependencies?: unknown[]): void => {
const effectBody = effect.toString();
const shouldCall = previousCalls.has(effectBody) ?
noDepsOrDifferent(previousCalls.get(effectBody), dependencies) :
true;
if (shouldCall) {
previousCalls.set(effectBody, dependencies);
if (cleanupFunctions.has(effectBody)) {
cleanupFunctions.get(effectBody)();
}
const cleanupFunction = effect();
if (typeof cleanupFunction === 'function') {
cleanupFunctions.set(effectBody, cleanupFunction);
}
}
}
};
export default mockUseEffect;