| 1 | "use strict"; |
| 2 | |
| 3 | /** |
| 4 | * @typedef {import('../runner.js')} Runner |
| 5 | * @typedef {import('../test.js')} Test |
| 6 | */ |
| 7 | |
| 8 | /** |
| 9 | * @module JSONStream |
| 10 | */ |
| 11 | /** |
| 12 | * Module dependencies. |
| 13 | */ |
| 14 | |
| 15 | var Base = require("./base"); |
| 16 | var constants = require("../runner").constants; |
| 17 | var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; |
| 18 | var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; |
| 19 | var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; |
| 20 | var EVENT_RUN_END = constants.EVENT_RUN_END; |
| 21 | |
| 22 | /** |
| 23 | * Expose `JSONStream`. |
| 24 | */ |
| 25 | |
| 26 | exports = module.exports = JSONStream; |
| 27 | |
| 28 | /** |
| 29 | * Constructs a new `JSONStream` reporter instance. |
| 30 | * |
| 31 | * @public |
| 32 | * @class |
| 33 | * @memberof Mocha.reporters |
| 34 | * @extends Mocha.reporters.Base |
| 35 | * @param {Runner} runner - Instance triggers reporter actions. |
| 36 | * @param {Object} [options] - runner options |
| 37 | */ |
| 38 | function JSONStream(runner, options) { |
| 39 | Base.call(this, runner, options); |
| 40 | |
| 41 | var self = this; |
| 42 | var total = runner.total; |
| 43 | |
| 44 | runner.once(EVENT_RUN_BEGIN, function () { |
| 45 | writeEvent(["start", { total }]); |
| 46 | }); |
| 47 | |
| 48 | runner.on(EVENT_TEST_PASS, function (test) { |
| 49 | writeEvent(["pass", clean(test)]); |
| 50 | }); |
| 51 | |
| 52 | runner.on(EVENT_TEST_FAIL, function (test, err) { |
| 53 | test = clean(test); |
| 54 | test.err = err.message; |
| 55 | test.stack = err.stack || null; |
| 56 | writeEvent(["fail", test]); |
| 57 | }); |
| 58 | |
| 59 | runner.once(EVENT_RUN_END, function () { |
| 60 | writeEvent(["end", self.stats]); |
| 61 | }); |
| 62 | } |
| 63 | |
| 64 | /** |
| 65 | * Writes Mocha event to reporter output stream. |
| 66 | * |
| 67 | * @private |
| 68 | * @param {unknown[]} event - Mocha event to be output. |
| 69 | */ |
| 70 | function writeEvent(event) { |
| 71 | process.stdout.write(JSON.stringify(event) + "\n"); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Returns an object literal representation of `test` |
| 76 | * free of cyclic properties, etc. |
| 77 | * |
| 78 | * @private |
| 79 | * @param {Test} test - Instance used as data source. |
| 80 | * @return {Object} object containing pared-down test instance data |
| 81 | */ |
| 82 | function clean(test) { |
| 83 | return { |
| 84 | title: test.title, |
| 85 | fullTitle: test.fullTitle(), |
| 86 | file: test.file, |
| 87 | duration: test.duration, |
| 88 | currentRetry: test.currentRetry(), |
| 89 | speed: test.speed, |
| 90 | }; |
| 91 | } |
| 92 | |
| 93 | JSONStream.description = "newline delimited JSON events"; |