json-stream.js 2.0 KB

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