hook.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. var Runnable = require('./runnable');
  3. const {inherits, constants} = require('./utils');
  4. const {MOCHA_ID_PROP_NAME} = constants;
  5. /**
  6. * Expose `Hook`.
  7. */
  8. module.exports = Hook;
  9. /**
  10. * Initialize a new `Hook` with the given `title` and callback `fn`
  11. *
  12. * @class
  13. * @extends Runnable
  14. * @param {String} title
  15. * @param {Function} fn
  16. */
  17. function Hook(title, fn) {
  18. Runnable.call(this, title, fn);
  19. this.type = 'hook';
  20. }
  21. /**
  22. * Inherit from `Runnable.prototype`.
  23. */
  24. inherits(Hook, Runnable);
  25. /**
  26. * Resets the state for a next run.
  27. */
  28. Hook.prototype.reset = function () {
  29. Runnable.prototype.reset.call(this);
  30. delete this._error;
  31. };
  32. /**
  33. * Get or set the test `err`.
  34. *
  35. * @memberof Hook
  36. * @public
  37. * @param {Error} err
  38. * @return {Error}
  39. */
  40. Hook.prototype.error = function (err) {
  41. if (!arguments.length) {
  42. err = this._error;
  43. this._error = null;
  44. return err;
  45. }
  46. this._error = err;
  47. };
  48. /**
  49. * Returns an object suitable for IPC.
  50. * Functions are represented by keys beginning with `$$`.
  51. * @private
  52. * @returns {Object}
  53. */
  54. Hook.prototype.serialize = function serialize() {
  55. return {
  56. $$currentRetry: this.currentRetry(),
  57. $$fullTitle: this.fullTitle(),
  58. $$isPending: Boolean(this.isPending()),
  59. $$titlePath: this.titlePath(),
  60. ctx:
  61. this.ctx && this.ctx.currentTest
  62. ? {
  63. currentTest: {
  64. title: this.ctx.currentTest.title,
  65. [MOCHA_ID_PROP_NAME]: this.ctx.currentTest.id
  66. }
  67. }
  68. : {},
  69. duration: this.duration,
  70. file: this.file,
  71. parent: {
  72. $$fullTitle: this.parent.fullTitle(),
  73. [MOCHA_ID_PROP_NAME]: this.parent.id
  74. },
  75. state: this.state,
  76. title: this.title,
  77. type: this.type,
  78. [MOCHA_ID_PROP_NAME]: this.id
  79. };
  80. };