UNPKG

1.98 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 return serializeObject(test, ['pending', 'context']);
30}
31
32const serializeObject = (obj, fields) => {
33 const result = obj.serialize();
34 for (let field of fields) {
35 // The field's started with `$$` are results of methods
36 result[field] = field.startsWith('$$') ? obj[field.slice(2)]() : obj[field];
37 }
38 if (result.err instanceof Error) {
39 result.err = serializeError(result.err);
40 }
41 return result;
42};
43
44const serializeError = error => {
45 /* The default properties of Error class: name, message and stack; are excluded from the enumeration.
46 It causes the following: JSON.stringify(new Error("FAKE")) === '{}'
47 So, we need to provide explicitly these properties to the JSON serializer. */
48 if (error instanceof Error) {
49 return {
50 message: error.message,
51 stack: error.stack,
52 name: error.name,
53 ...error,
54 };
55 }
56 return error;
57};
58
59module.exports = { serializeSuite, serializeHook, serializeTest, serializeObject, serializeError };