Skip to content

Commit

Permalink
fix circular objects in json reporter; closes #2433 (#3318)
Browse files Browse the repository at this point in the history
original work by @jeversmann; continuation of PR #2559 

Signed-off-by: Christopher Hiller <boneskull@boneskull.com>
  • Loading branch information
boneskull committed Apr 8, 2018
1 parent 8010501 commit 741b0bd
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
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
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 741b0bd

Please sign in to comment.