Skip to content

Commit 0a08636

Browse files
committed
test: introduce defer helper for resource cleanup in tests
This adds a new `defer` method to the mocha test context which allows us to call arbitrary async functions directly after a test has completed running.
1 parent 6793ed0 commit 0a08636

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

test/runner/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,5 +95,6 @@ before(function(_done) {
9595
after(() => mock.cleanup());
9696

9797
// optionally enable test runner-wide plugins
98+
require('./plugins/deferred');
9899
require('./plugins/session_leak_checker');
99100
require('./plugins/client_leak_checker');

test/runner/plugins/deferred.js

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
'use strict';
2+
const kDeferred = Symbol('deferred');
3+
4+
(mocha => {
5+
const Context = mocha.Context;
6+
function makeExecuteDeferred(test) {
7+
return () => {
8+
const deferredActions = test[kDeferred];
9+
10+
return Promise.all(
11+
Array.from(deferredActions).map(action => {
12+
if (action.length > 0) {
13+
// assume these are async methods with provided `done`
14+
return new Promise((resolve, reject) => {
15+
function done(err) {
16+
if (err) return reject(err);
17+
resolve();
18+
}
19+
20+
action(done);
21+
});
22+
}
23+
24+
// otherwise assume a Promise is returned
25+
action();
26+
})
27+
).then(() => {
28+
test[kDeferred].clear();
29+
});
30+
};
31+
}
32+
33+
Context.prototype.defer = function(fn) {
34+
const test = this.test;
35+
if (test[kDeferred] == null) {
36+
test[kDeferred] = new Set();
37+
38+
const parentSuite = test.parent;
39+
const afterEachHooks = parentSuite._afterEach;
40+
if (afterEachHooks[0] == null || afterEachHooks[0].title !== kDeferred) {
41+
const deferredHook = parentSuite._createHook('"deferred" hook', makeExecuteDeferred(test));
42+
43+
afterEachHooks.unshift(deferredHook);
44+
}
45+
}
46+
47+
test[kDeferred].add(fn);
48+
return this;
49+
};
50+
})(require('mocha'));

0 commit comments

Comments
 (0)