UNPKG

1.82 kBJavaScriptView Raw
1const debug = require('util').debuglog('egg-mock:register');
2const mock = require('./index').default;
3const agentHandler = require('./lib/agent_handler');
4const appHandler = require('./lib/app_handler');
5const injectContext = require('./lib/inject_context');
6
7exports.mochaGlobalSetup = async () => {
8 debug('mochaGlobalSetup, agent.setupAgent() start');
9 await agentHandler.setupAgent();
10 debug('mochaGlobalSetup, agent.setupAgent() end');
11};
12
13exports.mochaGlobalTeardown = async () => {
14 debug('mochaGlobalTeardown, agent.closeAgent() start');
15 await agentHandler.closeAgent();
16 debug('mochaGlobalTeardown, agent.closeAgent() end');
17};
18
19exports.mochaHooks = {
20 async beforeAll() {
21 const app = await appHandler.getApp();
22 debug('mochaHooks.beforeAll call, _app: %s', app);
23 if (app) {
24 await app.ready();
25 }
26 },
27 async afterEach() {
28 const app = await appHandler.getApp();
29 debug('mochaHooks.afterEach call, _app: %s', app);
30 if (app) {
31 await app.backgroundTasksFinished();
32 }
33 await mock.restore();
34 },
35 async afterAll() {
36 // skip auto app close on parallel
37 if (process.env.ENABLE_MOCHA_PARALLEL) return;
38 const app = await appHandler.getApp();
39 debug('mochaHooks.afterAll call, _app: %s', app);
40 if (app) {
41 await app.close();
42 }
43 },
44};
45
46/**
47 * Find active node mocha instances.
48 *
49 * @return {Array}
50 */
51function findNodeJSMocha() {
52 const children = require.cache || {};
53
54 return Object.keys(children)
55 .filter(function(child) {
56 const val = children[child].exports;
57 return typeof val === 'function' && val.name === 'Mocha';
58 })
59 .map(function(child) {
60 return children[child].exports;
61 });
62}
63
64require('mocha');
65const modules = findNodeJSMocha();
66
67for (const module of modules) {
68 injectContext(module);
69}
70