stats-collector.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. /**
  3. * Provides a factory function for a {@link StatsCollector} object.
  4. * @module
  5. */
  6. var constants = require('./runner').constants;
  7. var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
  8. var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
  9. var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
  10. var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
  11. var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
  12. var EVENT_RUN_END = constants.EVENT_RUN_END;
  13. var EVENT_TEST_END = constants.EVENT_TEST_END;
  14. /**
  15. * Test statistics collector.
  16. *
  17. * @public
  18. * @typedef {Object} StatsCollector
  19. * @property {number} suites - integer count of suites run.
  20. * @property {number} tests - integer count of tests run.
  21. * @property {number} passes - integer count of passing tests.
  22. * @property {number} pending - integer count of pending tests.
  23. * @property {number} failures - integer count of failed tests.
  24. * @property {Date} start - time when testing began.
  25. * @property {Date} end - time when testing concluded.
  26. * @property {number} duration - number of msecs that testing took.
  27. */
  28. var Date = global.Date;
  29. /**
  30. * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`.
  31. *
  32. * @private
  33. * @param {Runner} runner - Runner instance
  34. * @throws {TypeError} If falsy `runner`
  35. */
  36. function createStatsCollector(runner) {
  37. /**
  38. * @type StatsCollector
  39. */
  40. var stats = {
  41. suites: 0,
  42. tests: 0,
  43. passes: 0,
  44. pending: 0,
  45. failures: 0
  46. };
  47. if (!runner) {
  48. throw new TypeError('Missing runner argument');
  49. }
  50. runner.stats = stats;
  51. runner.once(EVENT_RUN_BEGIN, function() {
  52. stats.start = new Date();
  53. });
  54. runner.on(EVENT_SUITE_BEGIN, function(suite) {
  55. suite.root || stats.suites++;
  56. });
  57. runner.on(EVENT_TEST_PASS, function() {
  58. stats.passes++;
  59. });
  60. runner.on(EVENT_TEST_FAIL, function() {
  61. stats.failures++;
  62. });
  63. runner.on(EVENT_TEST_PENDING, function() {
  64. stats.pending++;
  65. });
  66. runner.on(EVENT_TEST_END, function() {
  67. stats.tests++;
  68. });
  69. runner.once(EVENT_RUN_END, function() {
  70. stats.end = new Date();
  71. stats.duration = stats.end - stats.start;
  72. });
  73. }
  74. module.exports = createStatsCollector;