-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathdeferred.js
More file actions
52 lines (40 loc) · 1.26 KB
/
deferred.js
File metadata and controls
52 lines (40 loc) · 1.26 KB
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
'use strict';
const kDeferred = Symbol('deferred');
const mocha = require('mocha');
const { Context } = mocha;
function makeExecuteDeferred(test) {
return async function () {
/** @type {Array<() => Promise<void>>} */
const deferredActions = test[kDeferred];
// process actions LIFO
const actions = Array.from(deferredActions).reverse();
try {
for (const fn of actions) {
await fn();
}
} finally {
test[kDeferred].length = 0;
}
};
}
Context.prototype.defer = function defer(fn) {
const test = this.test;
if (typeof fn !== 'function') {
throw new Error('defer is meant to take a function that returns a promise');
}
if (test[kDeferred] == null) {
test[kDeferred] = [];
const parentSuite = test.parent;
const afterEachHooks = parentSuite._afterEach;
if (afterEachHooks[0] == null || afterEachHooks[0].title !== kDeferred) {
const deferredHook = parentSuite._createHook('"deferred" hook', makeExecuteDeferred(test));
// defer runs after test but before afterEach(s)
afterEachHooks.unshift(deferredHook);
}
}
if (test[kDeferred].includes(fn)) {
throw new Error('registered the same deferred action more than once');
}
test[kDeferred].push(fn);
return this;
};