1 | const isObject = require('lodash.isobject');
|
2 | const isEmpty = require('lodash.isempty');
|
3 | const chalk = require('chalk');
|
4 | const stringify = require('json-stringify-safe');
|
5 |
|
6 | const errorPrefix = 'Error adding context:';
|
7 | const ERRORS = {
|
8 | INVALID_ARGS: `${errorPrefix} Invalid arguments.`,
|
9 | INVALID_TEST: `${errorPrefix} Invalid test object.`,
|
10 | INVALID_CONTEXT: ctx => {
|
11 | const expected =
|
12 | 'Expected a string or an object of shape { title: string, value: any } but saw:';
|
13 | return `${errorPrefix} ${expected}\n${stringify(
|
14 | ctx,
|
15 | (key, val) => (val === undefined ? 'undefined' : val),
|
16 | 2
|
17 | )}`;
|
18 | },
|
19 | };
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 | function log(msg, level) {
|
27 | const logMethod = console[level] || console.log;
|
28 | let out = msg;
|
29 | if (typeof msg === 'object') {
|
30 | out = stringify(msg, null, 2);
|
31 | }
|
32 | logMethod(`[${chalk.gray('mochawesome')}] ${out}\n`);
|
33 | }
|
34 |
|
35 | function _isValidContext(ctx) {
|
36 | |
37 |
|
38 |
|
39 |
|
40 |
|
41 | if (!ctx) return false;
|
42 | return (
|
43 | (typeof ctx === 'string' && !isEmpty(ctx)) ||
|
44 | (Object.hasOwnProperty.call(ctx, 'title') &&
|
45 | !isEmpty(ctx.title) &&
|
46 | Object.hasOwnProperty.call(ctx, 'value'))
|
47 | );
|
48 | }
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 |
|
79 | const addContext = function (...args) {
|
80 |
|
81 | if (args.length !== 2 || !isObject(args[0])) {
|
82 | log(ERRORS.INVALID_ARGS, 'error');
|
83 | return;
|
84 | }
|
85 |
|
86 | const ctx = args[1];
|
87 |
|
88 |
|
89 | if (!_isValidContext(ctx)) {
|
90 | log(ERRORS.INVALID_CONTEXT(ctx), 'error');
|
91 | return;
|
92 | }
|
93 |
|
94 | |
95 |
|
96 |
|
97 |
|
98 |
|
99 | const currentTest = args[0].currentTest;
|
100 | const activeTest = args[0].test;
|
101 |
|
102 | |
103 |
|
104 |
|
105 | const isEachHook =
|
106 | currentTest && /^"(?:before|after)\seach"/.test(activeTest.title);
|
107 | const test = isEachHook ? currentTest : activeTest;
|
108 |
|
109 | if (!test) {
|
110 | log(ERRORS.INVALID_TEST, 'error');
|
111 | return;
|
112 | }
|
113 |
|
114 | |
115 |
|
116 |
|
117 |
|
118 | if (ctx.title && ctx.value === undefined) {
|
119 | ctx.value = 'undefined';
|
120 | }
|
121 |
|
122 |
|
123 | if (!test.context) {
|
124 | test.context = ctx;
|
125 | } else if (Array.isArray(test.context)) {
|
126 |
|
127 | test.context.push(ctx);
|
128 | } else {
|
129 |
|
130 | test.context = [test.context];
|
131 | test.context.push(ctx);
|
132 | }
|
133 | };
|
134 |
|
135 | module.exports = addContext;
|