1 | const Mocha = require('mocha');
|
2 |
|
3 | const mochaSerializeSuite = Mocha.Suite.prototype.serialize;
|
4 |
|
5 |
|
6 | Mocha.Suite.prototype.serialize = function (...args) {
|
7 | if (this.root) {
|
8 |
|
9 | return serializeSuite(this);
|
10 | }
|
11 | return mochaSerializeSuite.apply(this, args)
|
12 | }
|
13 |
|
14 | const 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 |
|
24 | const serializeHook = hook => {
|
25 | return serializeObject(hook, ['body', 'state', 'err', 'context', '$$fullTitle']);
|
26 | }
|
27 |
|
28 | const serializeTest = test => {
|
29 | const result = serializeObject(test, ['pending', 'context']);
|
30 |
|
31 | result["$$retriedTest"] = null;
|
32 | return result;
|
33 | }
|
34 |
|
35 | const serializeObject = (obj, fields) => {
|
36 | const result = obj.serialize();
|
37 | for (let field of fields) {
|
38 |
|
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 |
|
47 | const serializeError = error => {
|
48 | |
49 |
|
50 |
|
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 |
|
62 | module.exports = { serializeSuite, serializeHook, serializeTest, serializeObject, serializeError };
|