mocha.js 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. 'use strict';
  2. /*!
  3. * mocha
  4. * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
  5. * MIT Licensed
  6. */
  7. var escapeRe = require('escape-string-regexp');
  8. var path = require('node:path');
  9. var builtinReporters = require('./reporters');
  10. var utils = require('./utils');
  11. var mocharc = require('./mocharc.json');
  12. var Suite = require('./suite');
  13. var esmUtils = require('./nodejs/esm-utils');
  14. var createStatsCollector = require('./stats-collector');
  15. const {
  16. createInvalidReporterError,
  17. createInvalidInterfaceError,
  18. createMochaInstanceAlreadyDisposedError,
  19. createMochaInstanceAlreadyRunningError,
  20. createUnsupportedError
  21. } = require('./errors');
  22. const {EVENT_FILE_PRE_REQUIRE, EVENT_FILE_POST_REQUIRE, EVENT_FILE_REQUIRE} =
  23. Suite.constants;
  24. var debug = require('debug')('mocha:mocha');
  25. /**
  26. * @typedef {import('./types.d.ts').DoneCB} DoneCB
  27. * @typedef {import('./types.d.ts').MochaGlobalFixture} MochaGlobalFixture
  28. * @typedef {import('./types.d.ts').MochaOptions} MochaOptions
  29. * @typedef {import('./types.d.ts').MochaRootHookObject} MochaRootHookObject
  30. * @typedef {import('./types.d.ts').Reporter} Reporter
  31. */
  32. exports = module.exports = Mocha;
  33. /**
  34. * A Mocha instance is a finite state machine.
  35. * These are the states it can be in.
  36. * @private
  37. */
  38. var mochaStates = utils.defineConstants({
  39. /**
  40. * Initial state of the mocha instance
  41. * @private
  42. */
  43. INIT: 'init',
  44. /**
  45. * Mocha instance is running tests
  46. * @private
  47. */
  48. RUNNING: 'running',
  49. /**
  50. * Mocha instance is done running tests and references to test functions and hooks are cleaned.
  51. * You can reset this state by unloading the test files.
  52. * @private
  53. */
  54. REFERENCES_CLEANED: 'referencesCleaned',
  55. /**
  56. * Mocha instance is disposed and can no longer be used.
  57. * @private
  58. */
  59. DISPOSED: 'disposed'
  60. });
  61. /**
  62. * To require local UIs and reporters when running in node.
  63. */
  64. if (!utils.isBrowser() && typeof module.paths !== 'undefined') {
  65. var cwd = utils.cwd();
  66. module.paths.push(cwd, path.join(cwd, 'node_modules'));
  67. }
  68. /**
  69. * Expose internals.
  70. * @private
  71. */
  72. exports.utils = utils;
  73. exports.interfaces = require('./interfaces');
  74. /**
  75. * @public
  76. * @memberof Mocha
  77. */
  78. exports.reporters = builtinReporters;
  79. exports.Runnable = require('./runnable');
  80. exports.Context = require('./context');
  81. /**
  82. *
  83. * @memberof Mocha
  84. */
  85. exports.Runner = require('./runner');
  86. exports.Suite = Suite;
  87. exports.Hook = require('./hook');
  88. exports.Test = require('./test');
  89. let currentContext;
  90. exports.afterEach = function (...args) {
  91. return (currentContext.afterEach || currentContext.teardown).apply(
  92. this,
  93. args
  94. );
  95. };
  96. exports.after = function (...args) {
  97. return (currentContext.after || currentContext.suiteTeardown).apply(
  98. this,
  99. args
  100. );
  101. };
  102. exports.beforeEach = function (...args) {
  103. return (currentContext.beforeEach || currentContext.setup).apply(this, args);
  104. };
  105. exports.before = function (...args) {
  106. return (currentContext.before || currentContext.suiteSetup).apply(this, args);
  107. };
  108. exports.describe = function (...args) {
  109. return (currentContext.describe || currentContext.suite).apply(this, args);
  110. };
  111. exports.describe.only = function (...args) {
  112. return (currentContext.describe || currentContext.suite).only.apply(
  113. this,
  114. args
  115. );
  116. };
  117. exports.describe.skip = function (...args) {
  118. return (currentContext.describe || currentContext.suite).skip.apply(
  119. this,
  120. args
  121. );
  122. };
  123. exports.it = function (...args) {
  124. return (currentContext.it || currentContext.test).apply(this, args);
  125. };
  126. exports.it.only = function (...args) {
  127. return (currentContext.it || currentContext.test).only.apply(this, args);
  128. };
  129. exports.it.skip = function (...args) {
  130. return (currentContext.it || currentContext.test).skip.apply(this, args);
  131. };
  132. exports.xdescribe = exports.describe.skip;
  133. exports.xit = exports.it.skip;
  134. exports.setup = exports.beforeEach;
  135. exports.suiteSetup = exports.before;
  136. exports.suiteTeardown = exports.after;
  137. exports.suite = exports.describe;
  138. exports.teardown = exports.afterEach;
  139. exports.test = exports.it;
  140. exports.run = function (...args) {
  141. return currentContext.run.apply(this, args);
  142. };
  143. /**
  144. * Constructs a new Mocha instance with `options`.
  145. *
  146. * @public
  147. * @class Mocha
  148. * @param {MochaOptions} [options] - Settings object.
  149. */
  150. function Mocha(options = {}) {
  151. options = {...mocharc, ...options};
  152. this.files = [];
  153. this.options = options;
  154. // root suite
  155. this.suite = new exports.Suite('', new exports.Context(), true);
  156. this._cleanReferencesAfterRun = true;
  157. this._state = mochaStates.INIT;
  158. this.grep(options.grep)
  159. .fgrep(options.fgrep)
  160. .ui(options.ui)
  161. .reporter(
  162. options.reporter,
  163. options['reporter-option'] ||
  164. options.reporterOption ||
  165. options.reporterOptions // for backwards compatibility
  166. )
  167. .slow(options.slow)
  168. .global(options.global);
  169. // this guard exists because Suite#timeout does not consider `undefined` to be valid input
  170. if (typeof options.timeout !== 'undefined') {
  171. this.timeout(options.timeout === false ? 0 : options.timeout);
  172. }
  173. if ('retries' in options) {
  174. this.retries(options.retries);
  175. }
  176. [
  177. 'allowUncaught',
  178. 'asyncOnly',
  179. 'bail',
  180. 'checkLeaks',
  181. 'color',
  182. 'delay',
  183. 'diff',
  184. 'dryRun',
  185. 'passOnFailingTestSuite',
  186. 'failZero',
  187. 'forbidOnly',
  188. 'forbidPending',
  189. 'fullTrace',
  190. 'inlineDiffs',
  191. 'invert'
  192. ].forEach(function (opt) {
  193. if (options[opt]) {
  194. this[opt]();
  195. }
  196. }, this);
  197. if (options.rootHooks) {
  198. this.rootHooks(options.rootHooks);
  199. }
  200. /**
  201. * The class which we'll instantiate in {@link Mocha#run}. Defaults to
  202. * {@link Runner} in serial mode; changes in parallel mode.
  203. * @memberof Mocha
  204. * @private
  205. */
  206. this._runnerClass = exports.Runner;
  207. /**
  208. * Whether or not to call {@link Mocha#loadFiles} implicitly when calling
  209. * {@link Mocha#run}. If this is `true`, then it's up to the consumer to call
  210. * {@link Mocha#loadFiles} _or_ {@link Mocha#loadFilesAsync}.
  211. * @private
  212. * @memberof Mocha
  213. */
  214. this._lazyLoadFiles = false;
  215. /**
  216. * It's useful for a Mocha instance to know if it's running in a worker process.
  217. * We could derive this via other means, but it's helpful to have a flag to refer to.
  218. * @memberof Mocha
  219. * @private
  220. */
  221. this.isWorker = Boolean(options.isWorker);
  222. this.globalSetup(options.globalSetup)
  223. .globalTeardown(options.globalTeardown)
  224. .enableGlobalSetup(options.enableGlobalSetup)
  225. .enableGlobalTeardown(options.enableGlobalTeardown);
  226. if (
  227. options.parallel &&
  228. (typeof options.jobs === 'undefined' || options.jobs > 1)
  229. ) {
  230. debug('attempting to enable parallel mode');
  231. this.parallelMode(true);
  232. }
  233. }
  234. /**
  235. * Enables or disables bailing on the first failure.
  236. *
  237. * @public
  238. * @see [CLI option](../#-bail-b)
  239. * @param {boolean} [bail=true] - Whether to bail on first error.
  240. * @returns {Mocha} this
  241. * @chainable
  242. */
  243. Mocha.prototype.bail = function (bail) {
  244. this.suite.bail(bail !== false);
  245. return this;
  246. };
  247. /**
  248. * @summary
  249. * Adds `file` to be loaded for execution.
  250. *
  251. * @description
  252. * Useful for generic setup code that must be included within test suite.
  253. *
  254. * @public
  255. * @see [CLI option](../#-file-filedirectoryglob)
  256. * @param {string} file - Pathname of file to be loaded.
  257. * @returns {Mocha} this
  258. * @chainable
  259. */
  260. Mocha.prototype.addFile = function (file) {
  261. this.files.push(file);
  262. return this;
  263. };
  264. /**
  265. * Sets reporter to `reporter`, defaults to "spec".
  266. *
  267. * @public
  268. * @see [CLI option](../#-reporter-name-r-name)
  269. * @see [Reporters](../#reporters)
  270. * @param {String|Reporter} reporterName - Reporter name or constructor.
  271. * @param {Object} [reporterOptions] - Options used to configure the reporter.
  272. * @returns {Mocha} this
  273. * @chainable
  274. * @throws {Error} if requested reporter cannot be loaded
  275. * @example
  276. *
  277. * // Use XUnit reporter and direct its output to file
  278. * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });
  279. */
  280. Mocha.prototype.reporter = function (reporterName, reporterOptions) {
  281. if (typeof reporterName === 'function') {
  282. this._reporter = reporterName;
  283. } else {
  284. reporterName = reporterName || 'spec';
  285. var reporter;
  286. // Try to load a built-in reporter.
  287. if (builtinReporters[reporterName]) {
  288. reporter = builtinReporters[reporterName];
  289. }
  290. // Try to load reporters from process.cwd() and node_modules
  291. if (!reporter) {
  292. let foundReporter;
  293. try {
  294. foundReporter = require.resolve(reporterName);
  295. reporter = require(foundReporter);
  296. } catch (err) {
  297. if (foundReporter) {
  298. throw createInvalidReporterError(err.message, foundReporter);
  299. }
  300. // Try to load reporters from a cwd-relative path
  301. try {
  302. reporter = require(path.resolve(reporterName));
  303. } catch (err) {
  304. throw createInvalidReporterError(err.message, reporterName);
  305. }
  306. }
  307. }
  308. this._reporter = reporter;
  309. }
  310. this.options.reporterOption = reporterOptions;
  311. // alias option name is used in built-in reporters xunit/tap/progress
  312. this.options.reporterOptions = reporterOptions;
  313. return this;
  314. };
  315. /**
  316. * Sets test UI `name`, defaults to "bdd".
  317. *
  318. * @public
  319. * @see [CLI option](../#-ui-name-u-name)
  320. * @see [Interface DSLs](../#interfaces)
  321. * @param {string|Function} [ui=bdd] - Interface name or class.
  322. * @returns {Mocha} this
  323. * @chainable
  324. * @throws {Error} if requested interface cannot be loaded
  325. */
  326. Mocha.prototype.ui = function (ui) {
  327. var bindInterface;
  328. if (typeof ui === 'function') {
  329. bindInterface = ui;
  330. } else {
  331. ui = ui || 'bdd';
  332. bindInterface = exports.interfaces[ui];
  333. if (!bindInterface) {
  334. try {
  335. bindInterface = require(ui);
  336. } catch (err) {
  337. throw createInvalidInterfaceError(`invalid interface '${ui}'`, ui);
  338. }
  339. }
  340. }
  341. bindInterface(this.suite);
  342. this.suite.on(EVENT_FILE_PRE_REQUIRE, function (context) {
  343. currentContext = context;
  344. });
  345. return this;
  346. };
  347. /**
  348. * Loads `files` prior to execution. Does not support ES Modules.
  349. *
  350. * @description
  351. * The implementation relies on Node's `require` to execute
  352. * the test interface functions and will be subject to its cache.
  353. * Supports only CommonJS modules. To load ES modules, use Mocha#loadFilesAsync.
  354. *
  355. * @private
  356. * @see {@link Mocha#addFile}
  357. * @see {@link Mocha#run}
  358. * @see {@link Mocha#unloadFiles}
  359. * @see {@link Mocha#loadFilesAsync}
  360. * @param {Function} [fn] - Callback invoked upon completion.
  361. */
  362. Mocha.prototype.loadFiles = function (fn) {
  363. var self = this;
  364. var suite = this.suite;
  365. this.files.forEach(function (file) {
  366. file = path.resolve(file);
  367. suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);
  368. suite.emit(EVENT_FILE_REQUIRE, require(file), file, self);
  369. suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);
  370. });
  371. fn && fn();
  372. };
  373. /**
  374. * Loads `files` prior to execution. Supports Node ES Modules.
  375. *
  376. * @description
  377. * The implementation relies on Node's `require` and `import` to execute
  378. * the test interface functions and will be subject to its cache.
  379. * Supports both CJS and ESM modules.
  380. *
  381. * @public
  382. * @see {@link Mocha#addFile}
  383. * @see {@link Mocha#run}
  384. * @see {@link Mocha#unloadFiles}
  385. * @param {Object} [options] - Settings object.
  386. * @param {Function} [options.esmDecorator] - Function invoked on esm module name right before importing it. By default will passthrough as is.
  387. * @returns {Promise}
  388. * @example
  389. *
  390. * // loads ESM (and CJS) test files asynchronously, then runs root suite
  391. * mocha.loadFilesAsync()
  392. * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0))
  393. * .catch(() => process.exitCode = 1);
  394. */
  395. Mocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) {
  396. var self = this;
  397. var suite = this.suite;
  398. this.lazyLoadFiles(true);
  399. return esmUtils.loadFilesAsync(
  400. this.files,
  401. function (file) {
  402. suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);
  403. },
  404. function (file, resultModule) {
  405. suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self);
  406. suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);
  407. },
  408. esmDecorator
  409. );
  410. };
  411. /**
  412. * Removes a previously loaded file from Node's `require` cache.
  413. *
  414. * @private
  415. * @static
  416. * @see {@link Mocha#unloadFiles}
  417. * @param {string} file - Pathname of file to be unloaded.
  418. */
  419. Mocha.unloadFile = function (file) {
  420. if (utils.isBrowser()) {
  421. throw createUnsupportedError(
  422. 'unloadFile() is only supported in a Node.js environment'
  423. );
  424. }
  425. return require('./nodejs/file-unloader').unloadFile(file);
  426. };
  427. /**
  428. * Unloads `files` from Node's `require` cache.
  429. *
  430. * @description
  431. * This allows required files to be "freshly" reloaded, providing the ability
  432. * to reuse a Mocha instance programmatically.
  433. * Note: does not clear ESM module files from the cache
  434. *
  435. * <strong>Intended for consumers &mdash; not used internally</strong>
  436. *
  437. * @public
  438. * @see {@link Mocha#run}
  439. * @returns {Mocha} this
  440. * @chainable
  441. */
  442. Mocha.prototype.unloadFiles = function () {
  443. if (this._state === mochaStates.DISPOSED) {
  444. throw createMochaInstanceAlreadyDisposedError(
  445. 'Mocha instance is already disposed, it cannot be used again.',
  446. this._cleanReferencesAfterRun,
  447. this
  448. );
  449. }
  450. this.files.forEach(function (file) {
  451. Mocha.unloadFile(file);
  452. });
  453. this._state = mochaStates.INIT;
  454. return this;
  455. };
  456. /**
  457. * Sets `grep` filter after escaping RegExp special characters.
  458. *
  459. * @public
  460. * @see {@link Mocha#grep}
  461. * @param {string} str - Value to be converted to a regexp.
  462. * @returns {Mocha} this
  463. * @chainable
  464. * @example
  465. *
  466. * // Select tests whose full title begins with `"foo"` followed by a period
  467. * mocha.fgrep('foo.');
  468. */
  469. Mocha.prototype.fgrep = function (str) {
  470. if (!str) {
  471. return this;
  472. }
  473. return this.grep(new RegExp(escapeRe(str)));
  474. };
  475. /**
  476. * @summary
  477. * Sets `grep` filter used to select specific tests for execution.
  478. *
  479. * @description
  480. * If `re` is a regexp-like string, it will be converted to regexp.
  481. * The regexp is tested against the full title of each test (i.e., the
  482. * name of the test preceded by titles of each its ancestral suites).
  483. * As such, using an <em>exact-match</em> fixed pattern against the
  484. * test name itself will not yield any matches.
  485. * <br>
  486. * <strong>Previous filter value will be overwritten on each call!</strong>
  487. *
  488. * @public
  489. * @see [CLI option](../#-grep-regexp-g-regexp)
  490. * @see {@link Mocha#fgrep}
  491. * @see {@link Mocha#invert}
  492. * @param {RegExp|String} re - Regular expression used to select tests.
  493. * @return {Mocha} this
  494. * @chainable
  495. * @example
  496. *
  497. * // Select tests whose full title contains `"match"`, ignoring case
  498. * mocha.grep(/match/i);
  499. * @example
  500. *
  501. * // Same as above but with regexp-like string argument
  502. * mocha.grep('/match/i');
  503. * @example
  504. *
  505. * // ## Anti-example
  506. * // Given embedded test `it('only-this-test')`...
  507. * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this!
  508. */
  509. Mocha.prototype.grep = function (re) {
  510. if (utils.isString(re)) {
  511. // extract args if it's regex-like, i.e: [string, pattern, flag]
  512. var arg = re.match(/^\/(.*)\/([gimy]{0,4})$|.*/);
  513. this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);
  514. } else {
  515. this.options.grep = re;
  516. }
  517. return this;
  518. };
  519. /**
  520. * Inverts `grep` matches.
  521. *
  522. * @public
  523. * @see {@link Mocha#grep}
  524. * @return {Mocha} this
  525. * @chainable
  526. * @example
  527. *
  528. * // Select tests whose full title does *not* contain `"match"`, ignoring case
  529. * mocha.grep(/match/i).invert();
  530. */
  531. Mocha.prototype.invert = function () {
  532. this.options.invert = true;
  533. return this;
  534. };
  535. /**
  536. * Enables or disables checking for global variables leaked while running tests.
  537. *
  538. * @public
  539. * @see [CLI option](../#-check-leaks)
  540. * @param {boolean} [checkLeaks=true] - Whether to check for global variable leaks.
  541. * @return {Mocha} this
  542. * @chainable
  543. */
  544. Mocha.prototype.checkLeaks = function (checkLeaks) {
  545. this.options.checkLeaks = checkLeaks !== false;
  546. return this;
  547. };
  548. /**
  549. * Enables or disables whether or not to dispose after each test run.
  550. * Disable this to ensure you can run the test suite multiple times.
  551. * If disabled, be sure to dispose mocha when you're done to prevent memory leaks.
  552. * @public
  553. * @see {@link Mocha#dispose}
  554. * @param {boolean} cleanReferencesAfterRun
  555. * @return {Mocha} this
  556. * @chainable
  557. */
  558. Mocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) {
  559. this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false;
  560. return this;
  561. };
  562. /**
  563. * Manually dispose this mocha instance. Mark this instance as `disposed` and unable to run more tests.
  564. * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector.
  565. * @public
  566. */
  567. Mocha.prototype.dispose = function () {
  568. if (this._state === mochaStates.RUNNING) {
  569. throw createMochaInstanceAlreadyRunningError(
  570. 'Cannot dispose while the mocha instance is still running tests.'
  571. );
  572. }
  573. this.unloadFiles();
  574. this._previousRunner && this._previousRunner.dispose();
  575. this.suite.dispose();
  576. this._state = mochaStates.DISPOSED;
  577. };
  578. /**
  579. * Displays full stack trace upon test failure.
  580. *
  581. * @public
  582. * @see [CLI option](../#-full-trace)
  583. * @param {boolean} [fullTrace=true] - Whether to print full stacktrace upon failure.
  584. * @return {Mocha} this
  585. * @chainable
  586. */
  587. Mocha.prototype.fullTrace = function (fullTrace) {
  588. this.options.fullTrace = fullTrace !== false;
  589. return this;
  590. };
  591. /**
  592. * Specifies whitelist of variable names to be expected in global scope.
  593. *
  594. * @public
  595. * @see [CLI option](../#-global-variable-name)
  596. * @see {@link Mocha#checkLeaks}
  597. * @param {String[]|String} global - Accepted global variable name(s).
  598. * @return {Mocha} this
  599. * @chainable
  600. * @example
  601. *
  602. * // Specify variables to be expected in global scope
  603. * mocha.global(['jQuery', 'MyLib']);
  604. */
  605. Mocha.prototype.global = function (global) {
  606. this.options.global = (this.options.global || [])
  607. .concat(global)
  608. .filter(Boolean)
  609. .filter(function (elt, idx, arr) {
  610. return arr.indexOf(elt) === idx;
  611. });
  612. return this;
  613. };
  614. // for backwards compatibility, 'globals' is an alias of 'global'
  615. Mocha.prototype.globals = Mocha.prototype.global;
  616. /**
  617. * Enables or disables TTY color output by screen-oriented reporters.
  618. *
  619. * @public
  620. * @see [CLI option](../#-color-c-colors)
  621. * @param {boolean} [color=true] - Whether to enable color output.
  622. * @return {Mocha} this
  623. * @chainable
  624. */
  625. Mocha.prototype.color = function (color) {
  626. this.options.color = color !== false;
  627. return this;
  628. };
  629. /**
  630. * Enables or disables reporter to use inline diffs (rather than +/-)
  631. * in test failure output.
  632. *
  633. * @public
  634. * @see [CLI option](../#-inline-diffs)
  635. * @param {boolean} [inlineDiffs=true] - Whether to use inline diffs.
  636. * @return {Mocha} this
  637. * @chainable
  638. */
  639. Mocha.prototype.inlineDiffs = function (inlineDiffs) {
  640. this.options.inlineDiffs = inlineDiffs !== false;
  641. return this;
  642. };
  643. /**
  644. * Enables or disables reporter to include diff in test failure output.
  645. *
  646. * @public
  647. * @see [CLI option](../#-diff)
  648. * @param {boolean} [diff=true] - Whether to show diff on failure.
  649. * @return {Mocha} this
  650. * @chainable
  651. */
  652. Mocha.prototype.diff = function (diff) {
  653. this.options.diff = diff !== false;
  654. return this;
  655. };
  656. /**
  657. * @summary
  658. * Sets timeout threshold value.
  659. *
  660. * @description
  661. * A string argument can use shorthand (such as "2s") and will be converted.
  662. * If the value is `0`, timeouts will be disabled.
  663. *
  664. * @public
  665. * @see [CLI option](../#-timeout-ms-t-ms)
  666. * @see [Timeouts](../#timeouts)
  667. * @param {number|string} msecs - Timeout threshold value.
  668. * @return {Mocha} this
  669. * @chainable
  670. * @example
  671. *
  672. * // Sets timeout to one second
  673. * mocha.timeout(1000);
  674. * @example
  675. *
  676. * // Same as above but using string argument
  677. * mocha.timeout('1s');
  678. */
  679. Mocha.prototype.timeout = function (msecs) {
  680. this.suite.timeout(msecs);
  681. return this;
  682. };
  683. /**
  684. * Sets the number of times to retry failed tests.
  685. *
  686. * @public
  687. * @see [CLI option](../#-retries-n)
  688. * @see [Retry Tests](../#retry-tests)
  689. * @param {number} retry - Number of times to retry failed tests.
  690. * @return {Mocha} this
  691. * @chainable
  692. * @example
  693. *
  694. * // Allow any failed test to retry one more time
  695. * mocha.retries(1);
  696. */
  697. Mocha.prototype.retries = function (retry) {
  698. this.suite.retries(retry);
  699. return this;
  700. };
  701. /**
  702. * Sets slowness threshold value.
  703. *
  704. * @public
  705. * @see [CLI option](../#-slow-ms-s-ms)
  706. * @param {number} msecs - Slowness threshold value.
  707. * @return {Mocha} this
  708. * @chainable
  709. * @example
  710. *
  711. * // Sets "slow" threshold to half a second
  712. * mocha.slow(500);
  713. * @example
  714. *
  715. * // Same as above but using string argument
  716. * mocha.slow('0.5s');
  717. */
  718. Mocha.prototype.slow = function (msecs) {
  719. this.suite.slow(msecs);
  720. return this;
  721. };
  722. /**
  723. * Forces all tests to either accept a `done` callback or return a promise.
  724. *
  725. * @public
  726. * @see [CLI option](../#-async-only-a)
  727. * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise.
  728. * @return {Mocha} this
  729. * @chainable
  730. */
  731. Mocha.prototype.asyncOnly = function (asyncOnly) {
  732. this.options.asyncOnly = asyncOnly !== false;
  733. return this;
  734. };
  735. /**
  736. * Disables syntax highlighting (in browser).
  737. *
  738. * @public
  739. * @return {Mocha} this
  740. * @chainable
  741. */
  742. Mocha.prototype.noHighlighting = function () {
  743. this.options.noHighlighting = true;
  744. return this;
  745. };
  746. /**
  747. * Enables or disables uncaught errors to propagate.
  748. *
  749. * @public
  750. * @see [CLI option](../#-allow-uncaught)
  751. * @param {boolean} [allowUncaught=true] - Whether to propagate uncaught errors.
  752. * @return {Mocha} this
  753. * @chainable
  754. */
  755. Mocha.prototype.allowUncaught = function (allowUncaught) {
  756. this.options.allowUncaught = allowUncaught !== false;
  757. return this;
  758. };
  759. /**
  760. * @summary
  761. * Delays root suite execution.
  762. *
  763. * @description
  764. * Used to perform async operations before any suites are run.
  765. *
  766. * @public
  767. * @see [delayed root suite](../#delayed-root-suite)
  768. * @returns {Mocha} this
  769. * @chainable
  770. */
  771. Mocha.prototype.delay = function delay() {
  772. this.options.delay = true;
  773. return this;
  774. };
  775. /**
  776. * Enables or disables running tests in dry-run mode.
  777. *
  778. * @public
  779. * @see [CLI option](../#-dry-run)
  780. * @param {boolean} [dryRun=true] - Whether to activate dry-run mode.
  781. * @return {Mocha} this
  782. * @chainable
  783. */
  784. Mocha.prototype.dryRun = function (dryRun) {
  785. this.options.dryRun = dryRun !== false;
  786. return this;
  787. };
  788. /**
  789. * Fails test run if no tests encountered with exit-code 1.
  790. *
  791. * @public
  792. * @see [CLI option](../#-fail-zero)
  793. * @param {boolean} [failZero=true] - Whether to fail test run.
  794. * @return {Mocha} this
  795. * @chainable
  796. */
  797. Mocha.prototype.failZero = function (failZero) {
  798. this.options.failZero = failZero !== false;
  799. return this;
  800. };
  801. /**
  802. * Fail test run if tests were failed.
  803. *
  804. * @public
  805. * @see [CLI option](../#-pass-on-failing-test-suite)
  806. * @param {boolean} [passOnFailingTestSuite=false] - Whether to fail test run.
  807. * @return {Mocha} this
  808. * @chainable
  809. */
  810. Mocha.prototype.passOnFailingTestSuite = function(passOnFailingTestSuite) {
  811. this.options.passOnFailingTestSuite = passOnFailingTestSuite === true;
  812. return this;
  813. };
  814. /**
  815. * Causes tests marked `only` to fail the suite.
  816. *
  817. * @public
  818. * @see [CLI option](../#-forbid-only)
  819. * @param {boolean} [forbidOnly=true] - Whether tests marked `only` fail the suite.
  820. * @returns {Mocha} this
  821. * @chainable
  822. */
  823. Mocha.prototype.forbidOnly = function (forbidOnly) {
  824. this.options.forbidOnly = forbidOnly !== false;
  825. return this;
  826. };
  827. /**
  828. * Causes pending tests and tests marked `skip` to fail the suite.
  829. *
  830. * @public
  831. * @see [CLI option](../#-forbid-pending)
  832. * @param {boolean} [forbidPending=true] - Whether pending tests fail the suite.
  833. * @returns {Mocha} this
  834. * @chainable
  835. */
  836. Mocha.prototype.forbidPending = function (forbidPending) {
  837. this.options.forbidPending = forbidPending !== false;
  838. return this;
  839. };
  840. /**
  841. * Throws an error if mocha is in the wrong state to be able to transition to a "running" state.
  842. * @private
  843. */
  844. Mocha.prototype._guardRunningStateTransition = function () {
  845. if (this._state === mochaStates.RUNNING) {
  846. throw createMochaInstanceAlreadyRunningError(
  847. 'Mocha instance is currently running tests, cannot start a next test run until this one is done',
  848. this
  849. );
  850. }
  851. if (
  852. this._state === mochaStates.DISPOSED ||
  853. this._state === mochaStates.REFERENCES_CLEANED
  854. ) {
  855. throw createMochaInstanceAlreadyDisposedError(
  856. 'Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.',
  857. this._cleanReferencesAfterRun,
  858. this
  859. );
  860. }
  861. };
  862. /**
  863. * Mocha version as specified by "package.json".
  864. *
  865. * @name Mocha#version
  866. * @type string
  867. * @readonly
  868. */
  869. Object.defineProperty(Mocha.prototype, 'version', {
  870. value: require('../package.json').version,
  871. configurable: false,
  872. enumerable: true,
  873. writable: false
  874. });
  875. /**
  876. * Runs root suite and invokes `fn()` when complete.
  877. *
  878. * @description
  879. * To run tests multiple times (or to run tests in files that are
  880. * already in the `require` cache), make sure to clear them from
  881. * the cache first!
  882. *
  883. * @public
  884. * @see {@link Mocha#unloadFiles}
  885. * @see {@link Runner#run}
  886. * @param {DoneCB} [fn] - Callback invoked when test execution completed.
  887. * @returns {import("./runner.js")} runner instance
  888. * @example
  889. *
  890. * // exit with non-zero status if there were test failures
  891. * mocha.run(failures => process.exitCode = failures ? 1 : 0);
  892. */
  893. Mocha.prototype.run = function (fn) {
  894. this._guardRunningStateTransition();
  895. this._state = mochaStates.RUNNING;
  896. if (this._previousRunner) {
  897. this._previousRunner.dispose();
  898. this.suite.reset();
  899. }
  900. if (this.files.length && !this._lazyLoadFiles) {
  901. this.loadFiles();
  902. }
  903. var suite = this.suite;
  904. var options = this.options;
  905. options.files = this.files;
  906. const runner = new this._runnerClass(suite, {
  907. cleanReferencesAfterRun: this._cleanReferencesAfterRun,
  908. delay: options.delay,
  909. dryRun: options.dryRun,
  910. failZero: options.failZero
  911. });
  912. createStatsCollector(runner);
  913. var reporter = new this._reporter(runner, options);
  914. runner.checkLeaks = options.checkLeaks === true;
  915. runner.fullStackTrace = options.fullTrace;
  916. runner.asyncOnly = options.asyncOnly;
  917. runner.allowUncaught = options.allowUncaught;
  918. runner.forbidOnly = options.forbidOnly;
  919. runner.forbidPending = options.forbidPending;
  920. if (options.grep) {
  921. runner.grep(options.grep, options.invert);
  922. }
  923. if (options.global) {
  924. runner.globals(options.global);
  925. }
  926. if (options.color !== undefined) {
  927. exports.reporters.Base.useColors = options.color;
  928. }
  929. exports.reporters.Base.inlineDiffs = options.inlineDiffs;
  930. exports.reporters.Base.hideDiff = !options.diff;
  931. const done = failures => {
  932. this._previousRunner = runner;
  933. this._state = this._cleanReferencesAfterRun
  934. ? mochaStates.REFERENCES_CLEANED
  935. : mochaStates.INIT;
  936. fn = fn || utils.noop;
  937. if (typeof reporter.done === 'function') {
  938. reporter.done(failures, fn);
  939. } else {
  940. fn(failures);
  941. }
  942. };
  943. const runAsync = async runner => {
  944. const context =
  945. this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()
  946. ? await this.runGlobalSetup(runner)
  947. : {};
  948. const failureCount = await runner.runAsync({
  949. files: this.files,
  950. options
  951. });
  952. if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) {
  953. await this.runGlobalTeardown(runner, {context});
  954. }
  955. return failureCount;
  956. };
  957. // no "catch" here is intentional. errors coming out of
  958. // Runner#run are considered uncaught/unhandled and caught
  959. // by the `process` event listeners.
  960. // also: returning anything other than `runner` would be a breaking
  961. // change
  962. runAsync(runner).then(done);
  963. return runner;
  964. };
  965. /**
  966. * Assigns hooks to the root suite
  967. * @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite
  968. * @chainable
  969. */
  970. Mocha.prototype.rootHooks = function rootHooks({
  971. beforeAll = [],
  972. beforeEach = [],
  973. afterAll = [],
  974. afterEach = []
  975. } = {}) {
  976. beforeAll = utils.castArray(beforeAll);
  977. beforeEach = utils.castArray(beforeEach);
  978. afterAll = utils.castArray(afterAll);
  979. afterEach = utils.castArray(afterEach);
  980. beforeAll.forEach(hook => {
  981. this.suite.beforeAll(hook);
  982. });
  983. beforeEach.forEach(hook => {
  984. this.suite.beforeEach(hook);
  985. });
  986. afterAll.forEach(hook => {
  987. this.suite.afterAll(hook);
  988. });
  989. afterEach.forEach(hook => {
  990. this.suite.afterEach(hook);
  991. });
  992. return this;
  993. };
  994. /**
  995. * Toggles parallel mode.
  996. *
  997. * Must be run before calling {@link Mocha#run}. Changes the `Runner` class to
  998. * use; also enables lazy file loading if not already done so.
  999. *
  1000. * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel
  1001. * mode, but parallel mode is _not_ a prerequisite for lazy loading!
  1002. * @param {boolean} [enable] - If `true`, enable; otherwise disable.
  1003. * @throws If run in browser
  1004. * @throws If Mocha not in `INIT` state
  1005. * @returns {Mocha}
  1006. * @chainable
  1007. * @public
  1008. */
  1009. Mocha.prototype.parallelMode = function parallelMode(enable = true) {
  1010. if (utils.isBrowser()) {
  1011. throw createUnsupportedError('parallel mode is only supported in Node.js');
  1012. }
  1013. const parallel = Boolean(enable);
  1014. if (
  1015. parallel === this.options.parallel &&
  1016. this._lazyLoadFiles &&
  1017. this._runnerClass !== exports.Runner
  1018. ) {
  1019. return this;
  1020. }
  1021. if (this._state !== mochaStates.INIT) {
  1022. throw createUnsupportedError(
  1023. 'cannot change parallel mode after having called run()'
  1024. );
  1025. }
  1026. this.options.parallel = parallel;
  1027. // swap Runner class
  1028. this._runnerClass = parallel
  1029. ? require('./nodejs/parallel-buffered-runner')
  1030. : exports.Runner;
  1031. // lazyLoadFiles may have been set `true` otherwise (for ESM loading),
  1032. // so keep `true` if so.
  1033. return this.lazyLoadFiles(this._lazyLoadFiles || parallel);
  1034. };
  1035. /**
  1036. * Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This
  1037. * setting is used by watch mode, parallel mode, and for loading ESM files.
  1038. * @todo This should throw if we've already loaded files; such behavior
  1039. * necessitates adding a new state.
  1040. * @param {boolean} [enable] - If `true`, disable eager loading of files in
  1041. * {@link Mocha#run}
  1042. * @chainable
  1043. * @public
  1044. */
  1045. Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
  1046. this._lazyLoadFiles = enable === true;
  1047. debug('set lazy load to %s', enable);
  1048. return this;
  1049. };
  1050. /**
  1051. * Configures one or more global setup fixtures.
  1052. *
  1053. * If given no parameters, _unsets_ any previously-set fixtures.
  1054. * @chainable
  1055. * @public
  1056. * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s)
  1057. * @returns {Mocha}
  1058. */
  1059. Mocha.prototype.globalSetup = function globalSetup(setupFns = []) {
  1060. setupFns = utils.castArray(setupFns);
  1061. this.options.globalSetup = setupFns;
  1062. debug('configured %d global setup functions', setupFns.length);
  1063. return this;
  1064. };
  1065. /**
  1066. * Configures one or more global teardown fixtures.
  1067. *
  1068. * If given no parameters, _unsets_ any previously-set fixtures.
  1069. * @chainable
  1070. * @public
  1071. * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s)
  1072. * @returns {Mocha}
  1073. */
  1074. Mocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) {
  1075. teardownFns = utils.castArray(teardownFns);
  1076. this.options.globalTeardown = teardownFns;
  1077. debug('configured %d global teardown functions', teardownFns.length);
  1078. return this;
  1079. };
  1080. /**
  1081. * Run any global setup fixtures sequentially, if any.
  1082. *
  1083. * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}.
  1084. *
  1085. * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}.
  1086. * @param {object} [context] - Context object if already have one
  1087. * @public
  1088. * @returns {Promise<object>} Context object
  1089. */
  1090. Mocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) {
  1091. const {globalSetup} = this.options;
  1092. if (globalSetup && globalSetup.length) {
  1093. debug('run(): global setup starting');
  1094. await this._runGlobalFixtures(globalSetup, context);
  1095. debug('run(): global setup complete');
  1096. }
  1097. return context;
  1098. };
  1099. /**
  1100. * Run any global teardown fixtures sequentially, if any.
  1101. *
  1102. * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}.
  1103. *
  1104. * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable.
  1105. * @param {object} [context] - Context object if already have one
  1106. * @public
  1107. * @returns {Promise<object>} Context object
  1108. */
  1109. Mocha.prototype.runGlobalTeardown = async function runGlobalTeardown(
  1110. context = {}
  1111. ) {
  1112. const {globalTeardown} = this.options;
  1113. if (globalTeardown && globalTeardown.length) {
  1114. debug('run(): global teardown starting');
  1115. await this._runGlobalFixtures(globalTeardown, context);
  1116. }
  1117. debug('run(): global teardown complete');
  1118. return context;
  1119. };
  1120. /**
  1121. * Run global fixtures sequentially with context `context`
  1122. * @private
  1123. * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run
  1124. * @param {object} [context] - context object
  1125. * @returns {Promise<object>} context object
  1126. */
  1127. Mocha.prototype._runGlobalFixtures = async function _runGlobalFixtures(
  1128. fixtureFns = [],
  1129. context = {}
  1130. ) {
  1131. for await (const fixtureFn of fixtureFns) {
  1132. await fixtureFn.call(context);
  1133. }
  1134. return context;
  1135. };
  1136. /**
  1137. * Toggle execution of any global setup fixture(s)
  1138. *
  1139. * @chainable
  1140. * @public
  1141. * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture
  1142. * @returns {Mocha}
  1143. */
  1144. Mocha.prototype.enableGlobalSetup = function enableGlobalSetup(enabled = true) {
  1145. this.options.enableGlobalSetup = Boolean(enabled);
  1146. return this;
  1147. };
  1148. /**
  1149. * Toggle execution of any global teardown fixture(s)
  1150. *
  1151. * @chainable
  1152. * @public
  1153. * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture
  1154. * @returns {Mocha}
  1155. */
  1156. Mocha.prototype.enableGlobalTeardown = function enableGlobalTeardown(
  1157. enabled = true
  1158. ) {
  1159. this.options.enableGlobalTeardown = Boolean(enabled);
  1160. return this;
  1161. };
  1162. /**
  1163. * Returns `true` if one or more global setup fixtures have been supplied.
  1164. * @public
  1165. * @returns {boolean}
  1166. */
  1167. Mocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() {
  1168. return Boolean(this.options.globalSetup.length);
  1169. };
  1170. /**
  1171. * Returns `true` if one or more global teardown fixtures have been supplied.
  1172. * @public
  1173. * @returns {boolean}
  1174. */
  1175. Mocha.prototype.hasGlobalTeardownFixtures =
  1176. function hasGlobalTeardownFixtures() {
  1177. return Boolean(this.options.globalTeardown.length);
  1178. };