From 76b36a1fda5a11098bedbfb0541109bbbf7a78dc Mon Sep 17 00:00:00 2001 From: Ashley Frieze Date: Fri, 28 Jan 2022 14:45:38 +0000 Subject: [PATCH] Add JSON Reporter output to object similar to #2651 --- lib/reporters/json.js | 10 +++++++++- test/reporters/json.spec.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/lib/reporters/json.js b/lib/reporters/json.js index 6194d8747d..58a94a8820 100644 --- a/lib/reporters/json.js +++ b/lib/reporters/json.js @@ -32,7 +32,8 @@ exports = module.exports = JSONReporter; * @memberof Mocha.reporters * @extends Mocha.reporters.Base * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options + * @param {Object} [options] - runner options - the property 'output' defines a target file to write to + * the property 'targetObject' an object into which the results of the tests will be written */ function JSONReporter(runner, options = {}) { Base.call(this, runner, options); @@ -43,6 +44,7 @@ function JSONReporter(runner, options = {}) { var failures = []; var passes = []; var output; + var targetObject; if (options.reporterOption && options.reporterOption.output) { if (utils.isBrowser()) { @@ -51,6 +53,10 @@ function JSONReporter(runner, options = {}) { output = options.reporterOption.output; } + if (options.reporterOption && 'targetObject' in options.reporterOption) { + targetObject = options.reporterOption.targetObject; + } + runner.on(EVENT_TEST_END, function (test) { tests.push(test); }); @@ -89,6 +95,8 @@ function JSONReporter(runner, options = {}) { ); process.stdout.write(json); } + } else if (targetObject !== undefined) { + Object.assign(targetObject, obj); } else { process.stdout.write(json); } diff --git a/test/reporters/json.spec.js b/test/reporters/json.spec.js index f1f1f87922..62ab976999 100644 --- a/test/reporters/json.spec.js +++ b/test/reporters/json.spec.js @@ -230,4 +230,33 @@ describe('JSON reporter', function () { ); }); }); + + describe('when "reporterOption.targetObject" is provided', function () { + var theObject = {}; + + var options = { + reporterOption: { + targetObject: theObject + } + }; + + beforeEach(function () { + /* eslint no-unused-vars: off */ + var mochaReporter = new mocha._reporter(runner, options); + }); + + beforeEach(function () { + // Add one test to suite to avoid assertions against empty test results + var test = new Test(testTitle, () => {}); + test.file = testFile; + suite.addTest(test); + }); + + it('should write test results to the object', function (done) { + runner.run(function () { + expect(theObject, 'not to be empty'); + done(); + }); + }); + }); });