-
-
Notifications
You must be signed in to change notification settings - Fork 259
/
Copy pathhelper-hooks.ts
63 lines (55 loc) · 2.31 KB
/
helper-hooks.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
type Hook = (...args: any[]) => void | Promise<void>;
type HookLabel = 'start' | 'end' | string;
type HookUnregister = {
unregister: () => void;
};
const registeredHooks = new Map<string, Set<Hook>>();
/**
* @private
* @param {string} helperName The name of the test helper in which to run the hook.
* @param {string} label A label to help identify the hook.
* @returns {string} The compound key for the helper.
*/
function getHelperKey(helperName: string, label: string) {
return `${helperName}:${label}`;
}
/**
* Registers a hook function to be run during the invocation of a test helper.
*
* @private
* @param {string} helperName The name of the test helper in which to run the hook.
* @param {string} label A label to help identify the hook. Built-in labels are `start` and `end`,
* designating the start of the helper invocation and the end.
* @param {Function} hook The hook function to run when the test helper is invoked.
* @returns {HookUnregister} An object containing an unregister function that will unregister
* the specific hook registered to the helper.
*/
export function registerHook(helperName: string, label: HookLabel, hook: Hook): HookUnregister {
let helperKey = getHelperKey(helperName, label);
let hooksForHelper = registeredHooks.get(helperKey);
if (hooksForHelper === undefined) {
hooksForHelper = new Set<Hook>();
registeredHooks.set(helperKey, hooksForHelper);
}
hooksForHelper.add(hook);
return {
unregister() {
hooksForHelper!.delete(hook);
},
};
}
/**
* Runs all hooks registered for a specific test helper.
*
* @private
* @param {string} helperName The name of the test helper.
* @param {string} label A label to help identify the hook. Built-in labels are `start` and `end`,
* designating the start of the helper invocation and the end.
* @param {any[]} args Any arguments originally passed to the test helper.
* @returns {Promise<void>} A promise representing the serial invocation of the hooks.
*/
export function runHooks(helperName: string, label: HookLabel, ...args: any[]): Promise<void> {
let hooks = registeredHooks.get(getHelperKey(helperName, label)) || new Set<Hook>();
let promises = [...hooks].map(hook => hook(...args));
return Promise.all(promises).then(() => {});
}