Skip to content

Commit

Permalink
Add JSON Reporter output to object similar to #2651
Browse files Browse the repository at this point in the history
  • Loading branch information
ashleyfrieze committed Jan 28, 2022
1 parent cc51b8f commit 76b36a1
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/reporters/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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()) {
Expand All @@ -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);
});
Expand Down Expand Up @@ -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);
}
Expand Down
29 changes: 29 additions & 0 deletions test/reporters/json.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});
});

0 comments on commit 76b36a1

Please sign in to comment.