stats-collector.js 1.7 KB

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