Skip to content

Commit

Permalink
feat(Mocha): Patch circular references parallel invocation bug
Browse files Browse the repository at this point in the history
  • Loading branch information
medikoo committed Jan 13, 2021
1 parent eccf774 commit 132453a
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion setup/patch.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,39 @@ const EventEmitter = require('events');

const runnerEmitter = new EventEmitter();

const isObject = require('type/object/is');
const Mocha = require('mocha/lib/mocha');
const { serialize } = require('mocha/lib/nodejs/serializer');

const removeCyclicReferences = (object, handled = new Set()) => {
handled.add(object);
const entries = Array.isArray(object) ? object.entries() : Object.entries(object);
for (const [key, value] of entries) {
if (!isObject(value)) continue;
if (handled.has(value)) delete object[key];
else removeCyclicReferences(value, new Set(handled));
}
};

const mochaRun = Mocha.prototype.run;
Mocha.prototype.run = function (fn, ...args) {
const runner = mochaRun.call(this, fn, ...args);
const runner = mochaRun.call(
this,
(result) => {
// Workaround https://github.com/mochajs/mocha/issues/4552
const serialized = serialize(result);
const stringifiedResult = (() => {
try {
return JSON.stringify(serialized);
} catch (error) {
removeCyclicReferences(serialized);
return JSON.stringify(serialized);
}
})();
return fn.call(this, JSON.parse(stringifiedResult));
},
...args
);
if (runner.constructor.name === 'Runner') runnerEmitter.emit('runner', runner);
runner.constructor.immediately = process.nextTick;
return runner;
Expand Down

0 comments on commit 132453a

Please sign in to comment.