Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix circular objects in json reporter; closes #2433 #3318

Merged
merged 3 commits into from Apr 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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)
};
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor issue. We need an empty line here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed


/**
* 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();
});
});
});