UNPKG

2.13 kBJavaScriptView Raw
1const Mocha = require('mocha');
2
3const mochaSerializeSuite = Mocha.Suite.prototype.serialize;
4
5// Serialize the full root suite state to count `Skipped` tests.
6Mocha.Suite.prototype.serialize = function (...args) {
7 if (this.root) {
8 // Skipping the EVENT_SUITE_BEGIN serialization can reduce data transfer via IPC by 25%
9 return serializeSuite(this);
10 }
11 return mochaSerializeSuite.apply(this, args)
12}
13
14const serializeSuite = (suite) => {
15 const result = suite.root ? mochaSerializeSuite.call(suite) : serializeObject(suite, ['file']);
16 result.suites = suite.suites.map(it => serializeSuite(it));
17 result.tests = suite.tests.map(it => serializeTest(it));
18 ['_beforeAll', '_beforeEach', '_afterEach', '_afterAll'].forEach(hookName => {
19 result[hookName] = suite[hookName].map(it => serializeHook(it))
20 });
21 return result;
22}
23
24const serializeHook = hook => {
25 return serializeObject(hook, ['body', 'state', 'err', 'context', '$$fullTitle']);
26}
27
28const serializeTest = test => {
29 const result = serializeObject(test, ['pending', 'context']);
30 // to remove a circular dependency: https://github.com/adamgruber/mochawesome/issues/356
31 result["$$retriedTest"] = null;
32 return result;
33}
34
35const serializeObject = (obj, fields) => {
36 const result = obj.serialize();
37 for (let field of fields) {
38 // The field's started with `$$` are results of methods
39 result[field] = field.startsWith('$$') ? obj[field.slice(2)]() : obj[field];
40 }
41 if (result.err instanceof Error) {
42 result.err = serializeError(result.err);
43 }
44 return result;
45};
46
47const serializeError = error => {
48 /* The default properties of Error class: name, message and stack; are excluded from the enumeration.
49 It causes the following: JSON.stringify(new Error("FAKE")) === '{}'
50 So, we need to provide explicitly these properties to the JSON serializer. */
51 if (error instanceof Error) {
52 return {
53 message: error.message,
54 stack: error.stack,
55 name: error.name,
56 ...error,
57 };
58 }
59 return error;
60};
61
62module.exports = { serializeSuite, serializeHook, serializeTest, serializeObject, serializeError };