json-stream.js 1.9 KB

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