Skip to content
This repository has been archived by the owner on Dec 4, 2023. It is now read-only.

Commit

Permalink
fix circular objects in json reporter; closes mochajs#2433 (mochajs#3318
Browse files Browse the repository at this point in the history
)

original work by @jeversmann; continuation of PR mochajs#2559 

Signed-off-by: Christopher Hiller <boneskull@boneskull.com>
  • Loading branch information
boneskull authored Apr 8, 2018
1 parent d1ff433 commit 54df67c
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 2 deletions.
31 changes: 29 additions & 2 deletions lib/reporters/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,44 @@ function JSONReporter (runner) {
* @return {Object}
*/
function clean (test) {
var err = test.err || {};
if (err instanceof Error) {
err = errorJSON(err);
}

return {
title: test.title,
fullTitle: test.fullTitle(),
duration: test.duration,
currentRetry: test.currentRetry(),
err: errorJSON(test.err || {})
err: cleanCycles(err)
};
}

/**
* Transform `error` into a JSON object.
* Replaces any circular references inside `obj` with '[object Object]'
*
* @api private
* @param {Object} obj
* @return {Object}
*/
function cleanCycles (obj) {
var cache = [];
return JSON.parse(JSON.stringify(obj, function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Instead of going in a circle, we'll print [object Object]
return '' + value;
}
cache.push(value);
}

return value;
}));
}

/**
* Transform an Error object into a JSON object.
*
* @api private
* @param {Error} err
Expand Down
27 changes: 27 additions & 0 deletions test/reporters/json.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,31 @@ describe('json reporter', function () {
done();
});
});

it('should handle circular objects in errors', function (done) {
var testTitle = 'json test 1';
function CircleError () {
this.message = 'oh shit';
this.circular = this;
}
var error = new CircleError();

suite.addTest(new Test(testTitle, function (done) {
throw error;
}));

runner.run(function (failureCount) {
expect(failureCount).to.equal(1);
expect(runner).to.have.property('testResults');
expect(runner.testResults).to.have.property('failures');
expect(runner.testResults.failures).to.be.an(Array);
expect(runner.testResults.failures).to.have.length(1);

var failure = runner.testResults.failures[0];
expect(failure).to.have.property('title', testTitle);
expect(failure).to.have.property('err');

done();
});
});
});

0 comments on commit 54df67c

Please sign in to comment.