diff --git a/bin/mocha.js b/bin/mocha.js old mode 100644 new mode 100755 diff --git a/docs/index.md b/docs/index.md index d63d3d0cfe..f03365da7c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1970,6 +1970,8 @@ The JSON reporter outputs a single large JSON object when the tests have complet By default, it will output to the console. To write directly to a file, use `--reporter-option output=filename.json`. +The indentation of the JSON reporter can be set with --reporter-option indentation=Number. Number being any integer. Alternatively, you can set the indentation to a tab character using --reporter-option indentation='\t'. + ![json reporter](images/reporter-json.png?withoutEnlargement&resize=920,9999){:class="screenshot" loading="lazy"} ### JSON Stream diff --git a/lib/reporters/json.js b/lib/reporters/json.js index 6194d8747d..7dff11c5fe 100644 --- a/lib/reporters/json.js +++ b/lib/reporters/json.js @@ -78,7 +78,16 @@ function JSONReporter(runner, options = {}) { runner.testResults = obj; - var json = JSON.stringify(obj, null, 2); + const indentation = options.reporterOption?.indentation?? 2; + + var json; + + if (indentation === '\\t') { + json = JSON.stringify(obj, null, '\t'); + } else { + json = JSON.stringify(obj, null, parseInt(indentation, 10)); + } + if (output) { try { fs.mkdirSync(path.dirname(output), {recursive: true}); diff --git a/test/reporters/json.spec.js b/test/reporters/json.spec.js index f1f1f87922..bcebca0b9b 100644 --- a/test/reporters/json.spec.js +++ b/test/reporters/json.spec.js @@ -229,5 +229,19 @@ describe('JSON reporter', function () { 'file output not supported in browser' ); }); + + it('should set options.indentation with a number', function () { + var options = {indentation: 4}; + var mochaReporter = new mocha._reporter(runner, options); + + expect(mochaReporter.options.indentation, 'to be', 4); + }); + + it('should set options.indentation correctly with a tab', function () { + var options = {indentation: '\t'}; + var mochaReporter = new mocha._reporter(runner, options); + + expect(mochaReporter.options.indentation, 'to be', '\t'); + }); }); });