UNPKG

2.23 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6const fibers_1 = __importDefault(require("./fibers"));
7const logger_1 = __importDefault(require("@wdio/logger"));
8const log = (0, logger_1.default)('@wdio/sync');
9/**
10 * Helper method to execute a row of hooks with certain parameters.
11 * It will return with a reject promise due to a design decision to not let hooks/service intefer the
12 * actual test process.
13 *
14 * @param {Function|Function[]} hooks list of hooks
15 * @param {Object[]} args list of parameter for hook functions
16 * @return {Promise} promise that gets resolved once all hooks finished running
17 */
18async function executeHooksWithArgs(hookName, hooks = [], args) {
19 /**
20 * make sure hooks are an array of functions
21 */
22 if (typeof hooks === 'function') {
23 hooks = [hooks];
24 }
25 /**
26 * make sure args is an array since we are calling apply
27 */
28 if (!Array.isArray(args)) {
29 args = [args];
30 }
31 const hookPromise = hooks.map((hook) => new Promise((resolve) => {
32 let result;
33 const execHook = () => {
34 delete global.browser._NOT_FIBER;
35 try {
36 result = hook.apply(null, args);
37 }
38 catch (err) {
39 log.error(err.stack);
40 return resolve(err);
41 }
42 if (result && typeof result.then === 'function') {
43 return result.then(resolve, (err) => {
44 log.error(err.stack);
45 resolve(err);
46 });
47 }
48 resolve(result);
49 };
50 /**
51 * after command hooks require additional Fiber environment
52 */
53 return hook.constructor.name === 'AsyncFunction' ? execHook() : (0, fibers_1.default)(execHook).run();
54 }));
55 const start = Date.now();
56 const result = await Promise.all(hookPromise);
57 if (hookPromise.length) {
58 log.debug(`Finished to run "${hookName}" hook in ${Date.now() - start}ms`);
59 }
60 return result;
61}
62exports.default = executeHooksWithArgs;