diff --git a/lib/reporters/json.js b/lib/reporters/json.js index aefde256b1..c0f808dbe3 100644 --- a/lib/reporters/json.js +++ b/lib/reporters/json.js @@ -54,18 +54,7 @@ function JSONReporter (runner) { runner.testResults = obj; - var cache = []; - process.stdout.write(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; - }, 2)); + process.stdout.write(JSON.stringify(obj, null, 2)); }); } @@ -78,17 +67,43 @@ 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) }; } +/** + * 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 `error` into a JSON object. + * Transform an Error object into a JSON object. * * @api private * @param {Error} err