30fab3ea458cb1e7c25f3802aeb834a31f54d944eb500817cfaec7ea2b23c6edd2b483390e30aa484f257d488f9b4404e9ec529252a0385858fff5ef974eb8 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280
  1. /**
  2. * The `node:test` module facilitates the creation of JavaScript tests.
  3. * To access it:
  4. *
  5. * ```js
  6. * import test from 'node:test';
  7. * ```
  8. *
  9. * This module is only available under the `node:` scheme. The following will not
  10. * work:
  11. *
  12. * ```js
  13. * import test from 'node:test';
  14. * ```
  15. *
  16. * Tests created via the `test` module consist of a single function that is
  17. * processed in one of three ways:
  18. *
  19. * 1. A synchronous function that is considered failing if it throws an exception,
  20. * and is considered passing otherwise.
  21. * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills.
  22. * 3. A function that receives a callback function. If the callback receives any
  23. * truthy value as its first argument, the test is considered failing. If a
  24. * falsy value is passed as the first argument to the callback, the test is
  25. * considered passing. If the test function receives a callback function and
  26. * also returns a `Promise`, the test will fail.
  27. *
  28. * The following example illustrates how tests are written using the `test` module.
  29. *
  30. * ```js
  31. * test('synchronous passing test', (t) => {
  32. * // This test passes because it does not throw an exception.
  33. * assert.strictEqual(1, 1);
  34. * });
  35. *
  36. * test('synchronous failing test', (t) => {
  37. * // This test fails because it throws an exception.
  38. * assert.strictEqual(1, 2);
  39. * });
  40. *
  41. * test('asynchronous passing test', async (t) => {
  42. * // This test passes because the Promise returned by the async
  43. * // function is settled and not rejected.
  44. * assert.strictEqual(1, 1);
  45. * });
  46. *
  47. * test('asynchronous failing test', async (t) => {
  48. * // This test fails because the Promise returned by the async
  49. * // function is rejected.
  50. * assert.strictEqual(1, 2);
  51. * });
  52. *
  53. * test('failing test using Promises', (t) => {
  54. * // Promises can be used directly as well.
  55. * return new Promise((resolve, reject) => {
  56. * setImmediate(() => {
  57. * reject(new Error('this will cause the test to fail'));
  58. * });
  59. * });
  60. * });
  61. *
  62. * test('callback passing test', (t, done) => {
  63. * // done() is the callback function. When the setImmediate() runs, it invokes
  64. * // done() with no arguments.
  65. * setImmediate(done);
  66. * });
  67. *
  68. * test('callback failing test', (t, done) => {
  69. * // When the setImmediate() runs, done() is invoked with an Error object and
  70. * // the test fails.
  71. * setImmediate(() => {
  72. * done(new Error('callback failure'));
  73. * });
  74. * });
  75. * ```
  76. *
  77. * If any tests fail, the process exit code is set to `1`.
  78. * @since v18.0.0, v16.17.0
  79. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js)
  80. */
  81. declare module "node:test" {
  82. import { Readable } from "node:stream";
  83. /**
  84. * **Note:** `shard` is used to horizontally parallelize test running across
  85. * machines or processes, ideal for large-scale executions across varied
  86. * environments. It's incompatible with `watch` mode, tailored for rapid
  87. * code iteration by automatically rerunning tests on file changes.
  88. *
  89. * ```js
  90. * import { tap } from 'node:test/reporters';
  91. * import { run } from 'node:test';
  92. * import process from 'node:process';
  93. * import path from 'node:path';
  94. *
  95. * run({ files: [path.resolve('./tests/test.js')] })
  96. * .compose(tap)
  97. * .pipe(process.stdout);
  98. * ```
  99. * @since v18.9.0, v16.19.0
  100. * @param options Configuration options for running tests.
  101. */
  102. function run(options?: RunOptions): TestsStream;
  103. /**
  104. * The `test()` function is the value imported from the `test` module. Each
  105. * invocation of this function results in reporting the test to the `TestsStream`.
  106. *
  107. * The `TestContext` object passed to the `fn` argument can be used to perform
  108. * actions related to the current test. Examples include skipping the test, adding
  109. * additional diagnostic information, or creating subtests.
  110. *
  111. * `test()` returns a `Promise` that fulfills once the test completes.
  112. * if `test()` is called within a suite, it fulfills immediately.
  113. * The return value can usually be discarded for top level tests.
  114. * However, the return value from subtests should be used to prevent the parent
  115. * test from finishing first and cancelling the subtest
  116. * as shown in the following example.
  117. *
  118. * ```js
  119. * test('top level test', async (t) => {
  120. * // The setTimeout() in the following subtest would cause it to outlive its
  121. * // parent test if 'await' is removed on the next line. Once the parent test
  122. * // completes, it will cancel any outstanding subtests.
  123. * await t.test('longer running subtest', async (t) => {
  124. * return new Promise((resolve, reject) => {
  125. * setTimeout(resolve, 1000);
  126. * });
  127. * });
  128. * });
  129. * ```
  130. *
  131. * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for
  132. * canceling tests because a running test might block the application thread and
  133. * thus prevent the scheduled cancellation.
  134. * @since v18.0.0, v16.17.0
  135. * @param name The name of the test, which is displayed when reporting test results.
  136. * Defaults to the `name` property of `fn`, or `'<anonymous>'` if `fn` does not have a name.
  137. * @param options Configuration options for the test.
  138. * @param fn The function under test. The first argument to this function is a {@link TestContext} object.
  139. * If the test uses callbacks, the callback function is passed as the second argument.
  140. * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite.
  141. */
  142. function test(name?: string, fn?: TestFn): Promise<void>;
  143. function test(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  144. function test(options?: TestOptions, fn?: TestFn): Promise<void>;
  145. function test(fn?: TestFn): Promise<void>;
  146. namespace test {
  147. export {
  148. after,
  149. afterEach,
  150. assert,
  151. before,
  152. beforeEach,
  153. describe,
  154. it,
  155. mock,
  156. only,
  157. run,
  158. skip,
  159. snapshot,
  160. suite,
  161. test,
  162. todo,
  163. };
  164. }
  165. /**
  166. * The `suite()` function is imported from the `node:test` module.
  167. * @param name The name of the suite, which is displayed when reporting test results.
  168. * Defaults to the `name` property of `fn`, or `'<anonymous>'` if `fn` does not have a name.
  169. * @param options Configuration options for the suite. This supports the same options as {@link test}.
  170. * @param fn The suite function declaring nested tests and suites. The first argument to this function is a {@link SuiteContext} object.
  171. * @return Immediately fulfilled with `undefined`.
  172. * @since v20.13.0
  173. */
  174. function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  175. function suite(name?: string, fn?: SuiteFn): Promise<void>;
  176. function suite(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  177. function suite(fn?: SuiteFn): Promise<void>;
  178. namespace suite {
  179. /**
  180. * Shorthand for skipping a suite. This is the same as calling {@link suite} with `options.skip` set to `true`.
  181. * @since v20.13.0
  182. */
  183. function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  184. function skip(name?: string, fn?: SuiteFn): Promise<void>;
  185. function skip(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  186. function skip(fn?: SuiteFn): Promise<void>;
  187. /**
  188. * Shorthand for marking a suite as `TODO`. This is the same as calling {@link suite} with `options.todo` set to `true`.
  189. * @since v20.13.0
  190. */
  191. function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  192. function todo(name?: string, fn?: SuiteFn): Promise<void>;
  193. function todo(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  194. function todo(fn?: SuiteFn): Promise<void>;
  195. /**
  196. * Shorthand for marking a suite as `only`. This is the same as calling {@link suite} with `options.only` set to `true`.
  197. * @since v20.13.0
  198. */
  199. function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  200. function only(name?: string, fn?: SuiteFn): Promise<void>;
  201. function only(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  202. function only(fn?: SuiteFn): Promise<void>;
  203. }
  204. /**
  205. * Alias for {@link suite}.
  206. *
  207. * The `describe()` function is imported from the `node:test` module.
  208. */
  209. function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  210. function describe(name?: string, fn?: SuiteFn): Promise<void>;
  211. function describe(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  212. function describe(fn?: SuiteFn): Promise<void>;
  213. namespace describe {
  214. /**
  215. * Shorthand for skipping a suite. This is the same as calling {@link describe} with `options.skip` set to `true`.
  216. * @since v18.15.0
  217. */
  218. function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  219. function skip(name?: string, fn?: SuiteFn): Promise<void>;
  220. function skip(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  221. function skip(fn?: SuiteFn): Promise<void>;
  222. /**
  223. * Shorthand for marking a suite as `TODO`. This is the same as calling {@link describe} with `options.todo` set to `true`.
  224. * @since v18.15.0
  225. */
  226. function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  227. function todo(name?: string, fn?: SuiteFn): Promise<void>;
  228. function todo(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  229. function todo(fn?: SuiteFn): Promise<void>;
  230. /**
  231. * Shorthand for marking a suite as `only`. This is the same as calling {@link describe} with `options.only` set to `true`.
  232. * @since v18.15.0
  233. */
  234. function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise<void>;
  235. function only(name?: string, fn?: SuiteFn): Promise<void>;
  236. function only(options?: TestOptions, fn?: SuiteFn): Promise<void>;
  237. function only(fn?: SuiteFn): Promise<void>;
  238. }
  239. /**
  240. * Alias for {@link test}.
  241. *
  242. * The `it()` function is imported from the `node:test` module.
  243. * @since v18.6.0, v16.17.0
  244. */
  245. function it(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  246. function it(name?: string, fn?: TestFn): Promise<void>;
  247. function it(options?: TestOptions, fn?: TestFn): Promise<void>;
  248. function it(fn?: TestFn): Promise<void>;
  249. namespace it {
  250. /**
  251. * Shorthand for skipping a test. This is the same as calling {@link it} with `options.skip` set to `true`.
  252. */
  253. function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  254. function skip(name?: string, fn?: TestFn): Promise<void>;
  255. function skip(options?: TestOptions, fn?: TestFn): Promise<void>;
  256. function skip(fn?: TestFn): Promise<void>;
  257. /**
  258. * Shorthand for marking a test as `TODO`. This is the same as calling {@link it} with `options.todo` set to `true`.
  259. */
  260. function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  261. function todo(name?: string, fn?: TestFn): Promise<void>;
  262. function todo(options?: TestOptions, fn?: TestFn): Promise<void>;
  263. function todo(fn?: TestFn): Promise<void>;
  264. /**
  265. * Shorthand for marking a test as `only`. This is the same as calling {@link it} with `options.only` set to `true`.
  266. * @since v18.15.0
  267. */
  268. function only(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  269. function only(name?: string, fn?: TestFn): Promise<void>;
  270. function only(options?: TestOptions, fn?: TestFn): Promise<void>;
  271. function only(fn?: TestFn): Promise<void>;
  272. }
  273. /**
  274. * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`.
  275. * @since v20.2.0
  276. */
  277. function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  278. function skip(name?: string, fn?: TestFn): Promise<void>;
  279. function skip(options?: TestOptions, fn?: TestFn): Promise<void>;
  280. function skip(fn?: TestFn): Promise<void>;
  281. /**
  282. * Shorthand for marking a test as `TODO`. This is the same as calling {@link test} with `options.todo` set to `true`.
  283. * @since v20.2.0
  284. */
  285. function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  286. function todo(name?: string, fn?: TestFn): Promise<void>;
  287. function todo(options?: TestOptions, fn?: TestFn): Promise<void>;
  288. function todo(fn?: TestFn): Promise<void>;
  289. /**
  290. * Shorthand for marking a test as `only`. This is the same as calling {@link test} with `options.only` set to `true`.
  291. * @since v20.2.0
  292. */
  293. function only(name?: string, options?: TestOptions, fn?: TestFn): Promise<void>;
  294. function only(name?: string, fn?: TestFn): Promise<void>;
  295. function only(options?: TestOptions, fn?: TestFn): Promise<void>;
  296. function only(fn?: TestFn): Promise<void>;
  297. /**
  298. * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object.
  299. * If the test uses callbacks, the callback function is passed as the second argument.
  300. */
  301. type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise<void>;
  302. /**
  303. * The type of a suite test function. The argument to this function is a {@link SuiteContext} object.
  304. */
  305. type SuiteFn = (s: SuiteContext) => void | Promise<void>;
  306. interface TestShard {
  307. /**
  308. * A positive integer between 1 and `total` that specifies the index of the shard to run.
  309. */
  310. index: number;
  311. /**
  312. * A positive integer that specifies the total number of shards to split the test files to.
  313. */
  314. total: number;
  315. }
  316. interface RunOptions {
  317. /**
  318. * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file.
  319. * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time.
  320. * @default false
  321. */
  322. concurrency?: number | boolean | undefined;
  323. /**
  324. * An array containing the list of files to run. If omitted, files are run according to the
  325. * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model).
  326. */
  327. files?: readonly string[] | undefined;
  328. /**
  329. * Configures the test runner to exit the process once all known
  330. * tests have finished executing even if the event loop would
  331. * otherwise remain active.
  332. * @default false
  333. */
  334. forceExit?: boolean | undefined;
  335. /**
  336. * An array containing the list of glob patterns to match test files.
  337. * This option cannot be used together with `files`. If omitted, files are run according to the
  338. * [test runner execution model](https://nodejs.org/docs/latest-v22.x/api/test.html#test-runner-execution-model).
  339. * @since v22.6.0
  340. */
  341. globPatterns?: readonly string[] | undefined;
  342. /**
  343. * Sets inspector port of test child process.
  344. * This can be a number, or a function that takes no arguments and returns a
  345. * number. If a nullish value is provided, each process gets its own port,
  346. * incremented from the primary's `process.debugPort`. This option is ignored
  347. * if the `isolation` option is set to `'none'` as no child processes are
  348. * spawned.
  349. * @default undefined
  350. */
  351. inspectPort?: number | (() => number) | undefined;
  352. /**
  353. * Configures the type of test isolation. If set to
  354. * `'process'`, each test file is run in a separate child process. If set to
  355. * `'none'`, all test files run in the current process.
  356. * @default 'process'
  357. * @since v22.8.0
  358. */
  359. isolation?: "process" | "none" | undefined;
  360. /**
  361. * If truthy, the test context will only run tests that have the `only` option set
  362. */
  363. only?: boolean | undefined;
  364. /**
  365. * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run.
  366. * @default undefined
  367. */
  368. setup?: ((reporter: TestsStream) => void | Promise<void>) | undefined;
  369. /**
  370. * An array of CLI flags to pass to the `node` executable when
  371. * spawning the subprocesses. This option has no effect when `isolation` is `'none`'.
  372. * @since v22.10.0
  373. * @default []
  374. */
  375. execArgv?: readonly string[] | undefined;
  376. /**
  377. * An array of CLI flags to pass to each test file when spawning the
  378. * subprocesses. This option has no effect when `isolation` is `'none'`.
  379. * @since v22.10.0
  380. * @default []
  381. */
  382. argv?: readonly string[] | undefined;
  383. /**
  384. * Allows aborting an in-progress test execution.
  385. */
  386. signal?: AbortSignal | undefined;
  387. /**
  388. * If provided, only run tests whose name matches the provided pattern.
  389. * Strings are interpreted as JavaScript regular expressions.
  390. * @default undefined
  391. */
  392. testNamePatterns?: string | RegExp | ReadonlyArray<string | RegExp> | undefined;
  393. /**
  394. * A String, RegExp or a RegExp Array, that can be used to exclude running tests whose
  395. * name matches the provided pattern. Test name patterns are interpreted as JavaScript
  396. * regular expressions. For each test that is executed, any corresponding test hooks,
  397. * such as `beforeEach()`, are also run.
  398. * @default undefined
  399. * @since v22.1.0
  400. */
  401. testSkipPatterns?: string | RegExp | ReadonlyArray<string | RegExp> | undefined;
  402. /**
  403. * The number of milliseconds after which the test execution will fail.
  404. * If unspecified, subtests inherit this value from their parent.
  405. * @default Infinity
  406. */
  407. timeout?: number | undefined;
  408. /**
  409. * Whether to run in watch mode or not.
  410. * @default false
  411. */
  412. watch?: boolean | undefined;
  413. /**
  414. * Running tests in a specific shard.
  415. * @default undefined
  416. */
  417. shard?: TestShard | undefined;
  418. /**
  419. * enable [code coverage](https://nodejs.org/docs/latest-v22.x/api/test.html#collecting-code-coverage) collection.
  420. * @since v22.10.0
  421. * @default false
  422. */
  423. coverage?: boolean | undefined;
  424. /**
  425. * Excludes specific files from code coverage
  426. * using a glob pattern, which can match both absolute and relative file paths.
  427. * This property is only applicable when `coverage` was set to `true`.
  428. * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided,
  429. * files must meet **both** criteria to be included in the coverage report.
  430. * @since v22.10.0
  431. * @default undefined
  432. */
  433. coverageExcludeGlobs?: string | readonly string[] | undefined;
  434. /**
  435. * Includes specific files in code coverage
  436. * using a glob pattern, which can match both absolute and relative file paths.
  437. * This property is only applicable when `coverage` was set to `true`.
  438. * If both `coverageExcludeGlobs` and `coverageIncludeGlobs` are provided,
  439. * files must meet **both** criteria to be included in the coverage report.
  440. * @since v22.10.0
  441. * @default undefined
  442. */
  443. coverageIncludeGlobs?: string | readonly string[] | undefined;
  444. /**
  445. * Require a minimum percent of covered lines. If code
  446. * coverage does not reach the threshold specified, the process will exit with code `1`.
  447. * @since v22.10.0
  448. * @default 0
  449. */
  450. lineCoverage?: number | undefined;
  451. /**
  452. * Require a minimum percent of covered branches. If code
  453. * coverage does not reach the threshold specified, the process will exit with code `1`.
  454. * @since v22.10.0
  455. * @default 0
  456. */
  457. branchCoverage?: number | undefined;
  458. /**
  459. * Require a minimum percent of covered functions. If code
  460. * coverage does not reach the threshold specified, the process will exit with code `1`.
  461. * @since v22.10.0
  462. * @default 0
  463. */
  464. functionCoverage?: number | undefined;
  465. }
  466. /**
  467. * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests.
  468. *
  469. * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute.
  470. * @since v18.9.0, v16.19.0
  471. */
  472. class TestsStream extends Readable implements NodeJS.ReadableStream {
  473. addListener(event: "test:coverage", listener: (data: TestCoverage) => void): this;
  474. addListener(event: "test:complete", listener: (data: TestComplete) => void): this;
  475. addListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this;
  476. addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
  477. addListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this;
  478. addListener(event: "test:fail", listener: (data: TestFail) => void): this;
  479. addListener(event: "test:pass", listener: (data: TestPass) => void): this;
  480. addListener(event: "test:plan", listener: (data: TestPlan) => void): this;
  481. addListener(event: "test:start", listener: (data: TestStart) => void): this;
  482. addListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
  483. addListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
  484. addListener(event: "test:summary", listener: (data: TestSummary) => void): this;
  485. addListener(event: "test:watch:drained", listener: () => void): this;
  486. addListener(event: string, listener: (...args: any[]) => void): this;
  487. emit(event: "test:coverage", data: TestCoverage): boolean;
  488. emit(event: "test:complete", data: TestComplete): boolean;
  489. emit(event: "test:dequeue", data: TestDequeue): boolean;
  490. emit(event: "test:diagnostic", data: DiagnosticData): boolean;
  491. emit(event: "test:enqueue", data: TestEnqueue): boolean;
  492. emit(event: "test:fail", data: TestFail): boolean;
  493. emit(event: "test:pass", data: TestPass): boolean;
  494. emit(event: "test:plan", data: TestPlan): boolean;
  495. emit(event: "test:start", data: TestStart): boolean;
  496. emit(event: "test:stderr", data: TestStderr): boolean;
  497. emit(event: "test:stdout", data: TestStdout): boolean;
  498. emit(event: "test:summary", data: TestSummary): boolean;
  499. emit(event: "test:watch:drained"): boolean;
  500. emit(event: string | symbol, ...args: any[]): boolean;
  501. on(event: "test:coverage", listener: (data: TestCoverage) => void): this;
  502. on(event: "test:complete", listener: (data: TestComplete) => void): this;
  503. on(event: "test:dequeue", listener: (data: TestDequeue) => void): this;
  504. on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
  505. on(event: "test:enqueue", listener: (data: TestEnqueue) => void): this;
  506. on(event: "test:fail", listener: (data: TestFail) => void): this;
  507. on(event: "test:pass", listener: (data: TestPass) => void): this;
  508. on(event: "test:plan", listener: (data: TestPlan) => void): this;
  509. on(event: "test:start", listener: (data: TestStart) => void): this;
  510. on(event: "test:stderr", listener: (data: TestStderr) => void): this;
  511. on(event: "test:stdout", listener: (data: TestStdout) => void): this;
  512. on(event: "test:summary", listener: (data: TestSummary) => void): this;
  513. on(event: "test:watch:drained", listener: () => void): this;
  514. on(event: string, listener: (...args: any[]) => void): this;
  515. once(event: "test:coverage", listener: (data: TestCoverage) => void): this;
  516. once(event: "test:complete", listener: (data: TestComplete) => void): this;
  517. once(event: "test:dequeue", listener: (data: TestDequeue) => void): this;
  518. once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
  519. once(event: "test:enqueue", listener: (data: TestEnqueue) => void): this;
  520. once(event: "test:fail", listener: (data: TestFail) => void): this;
  521. once(event: "test:pass", listener: (data: TestPass) => void): this;
  522. once(event: "test:plan", listener: (data: TestPlan) => void): this;
  523. once(event: "test:start", listener: (data: TestStart) => void): this;
  524. once(event: "test:stderr", listener: (data: TestStderr) => void): this;
  525. once(event: "test:stdout", listener: (data: TestStdout) => void): this;
  526. once(event: "test:summary", listener: (data: TestSummary) => void): this;
  527. once(event: "test:watch:drained", listener: () => void): this;
  528. once(event: string, listener: (...args: any[]) => void): this;
  529. prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this;
  530. prependListener(event: "test:complete", listener: (data: TestComplete) => void): this;
  531. prependListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this;
  532. prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
  533. prependListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this;
  534. prependListener(event: "test:fail", listener: (data: TestFail) => void): this;
  535. prependListener(event: "test:pass", listener: (data: TestPass) => void): this;
  536. prependListener(event: "test:plan", listener: (data: TestPlan) => void): this;
  537. prependListener(event: "test:start", listener: (data: TestStart) => void): this;
  538. prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
  539. prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
  540. prependListener(event: "test:summary", listener: (data: TestSummary) => void): this;
  541. prependListener(event: "test:watch:drained", listener: () => void): this;
  542. prependListener(event: string, listener: (...args: any[]) => void): this;
  543. prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this;
  544. prependOnceListener(event: "test:complete", listener: (data: TestComplete) => void): this;
  545. prependOnceListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this;
  546. prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this;
  547. prependOnceListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this;
  548. prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this;
  549. prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this;
  550. prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this;
  551. prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this;
  552. prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this;
  553. prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this;
  554. prependOnceListener(event: "test:summary", listener: (data: TestSummary) => void): this;
  555. prependOnceListener(event: "test:watch:drained", listener: () => void): this;
  556. prependOnceListener(event: string, listener: (...args: any[]) => void): this;
  557. }
  558. /**
  559. * An instance of `TestContext` is passed to each test function in order to
  560. * interact with the test runner. However, the `TestContext` constructor is not
  561. * exposed as part of the API.
  562. * @since v18.0.0, v16.17.0
  563. */
  564. class TestContext {
  565. /**
  566. * An object containing assertion methods bound to the test context.
  567. * The top-level functions from the `node:assert` module are exposed here for the purpose of creating test plans.
  568. *
  569. * **Note:** Some of the functions from `node:assert` contain type assertions. If these are called via the
  570. * TestContext `assert` object, then the context parameter in the test's function signature **must be explicitly typed**
  571. * (ie. the parameter must have a type annotation), otherwise an error will be raised by the TypeScript compiler:
  572. * ```ts
  573. * import { test, type TestContext } from 'node:test';
  574. *
  575. * // The test function's context parameter must have a type annotation.
  576. * test('example', (t: TestContext) => {
  577. * t.assert.deepStrictEqual(actual, expected);
  578. * });
  579. *
  580. * // Omitting the type annotation will result in a compilation error.
  581. * test('example', t => {
  582. * t.assert.deepStrictEqual(actual, expected); // Error: 't' needs an explicit type annotation.
  583. * });
  584. * ```
  585. * @since v22.2.0, v20.15.0
  586. */
  587. readonly assert: TestContextAssert;
  588. /**
  589. * This function is used to create a hook running before subtest of the current test.
  590. * @param fn The hook function. The first argument to this function is a `TestContext` object.
  591. * If the hook uses callbacks, the callback function is passed as the second argument.
  592. * @param options Configuration options for the hook.
  593. * @since v20.1.0, v18.17.0
  594. */
  595. before(fn?: TestContextHookFn, options?: HookOptions): void;
  596. /**
  597. * This function is used to create a hook running before each subtest of the current test.
  598. * @param fn The hook function. The first argument to this function is a `TestContext` object.
  599. * If the hook uses callbacks, the callback function is passed as the second argument.
  600. * @param options Configuration options for the hook.
  601. * @since v18.8.0
  602. */
  603. beforeEach(fn?: TestContextHookFn, options?: HookOptions): void;
  604. /**
  605. * This function is used to create a hook that runs after the current test finishes.
  606. * @param fn The hook function. The first argument to this function is a `TestContext` object.
  607. * If the hook uses callbacks, the callback function is passed as the second argument.
  608. * @param options Configuration options for the hook.
  609. * @since v18.13.0
  610. */
  611. after(fn?: TestContextHookFn, options?: HookOptions): void;
  612. /**
  613. * This function is used to create a hook running after each subtest of the current test.
  614. * @param fn The hook function. The first argument to this function is a `TestContext` object.
  615. * If the hook uses callbacks, the callback function is passed as the second argument.
  616. * @param options Configuration options for the hook.
  617. * @since v18.8.0
  618. */
  619. afterEach(fn?: TestContextHookFn, options?: HookOptions): void;
  620. /**
  621. * This function is used to write diagnostics to the output. Any diagnostic
  622. * information is included at the end of the test's results. This function does
  623. * not return a value.
  624. *
  625. * ```js
  626. * test('top level test', (t) => {
  627. * t.diagnostic('A diagnostic message');
  628. * });
  629. * ```
  630. * @since v18.0.0, v16.17.0
  631. * @param message Message to be reported.
  632. */
  633. diagnostic(message: string): void;
  634. /**
  635. * The absolute path of the test file that created the current test. If a test file imports
  636. * additional modules that generate tests, the imported tests will return the path of the root test file.
  637. * @since v22.6.0
  638. */
  639. readonly filePath: string | undefined;
  640. /**
  641. * The name of the test and each of its ancestors, separated by `>`.
  642. * @since v22.3.0
  643. */
  644. readonly fullName: string;
  645. /**
  646. * The name of the test.
  647. * @since v18.8.0, v16.18.0
  648. */
  649. readonly name: string;
  650. /**
  651. * This function is used to set the number of assertions and subtests that are expected to run
  652. * within the test. If the number of assertions and subtests that run does not match the
  653. * expected count, the test will fail.
  654. *
  655. * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly.
  656. *
  657. * ```js
  658. * test('top level test', (t) => {
  659. * t.plan(2);
  660. * t.assert.ok('some relevant assertion here');
  661. * t.test('subtest', () => {});
  662. * });
  663. * ```
  664. *
  665. * When working with asynchronous code, the `plan` function can be used to ensure that the
  666. * correct number of assertions are run:
  667. *
  668. * ```js
  669. * test('planning with streams', (t, done) => {
  670. * function* generate() {
  671. * yield 'a';
  672. * yield 'b';
  673. * yield 'c';
  674. * }
  675. * const expected = ['a', 'b', 'c'];
  676. * t.plan(expected.length);
  677. * const stream = Readable.from(generate());
  678. * stream.on('data', (chunk) => {
  679. * t.assert.strictEqual(chunk, expected.shift());
  680. * });
  681. *
  682. * stream.on('end', () => {
  683. * done();
  684. * });
  685. * });
  686. * ```
  687. *
  688. * When using the `wait` option, you can control how long the test will wait for the expected assertions.
  689. * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions
  690. * to complete within the specified timeframe:
  691. *
  692. * ```js
  693. * test('plan with wait: 2000 waits for async assertions', (t) => {
  694. * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete.
  695. *
  696. * const asyncActivity = () => {
  697. * setTimeout(() => {
  698. * * t.assert.ok(true, 'Async assertion completed within the wait time');
  699. * }, 1000); // Completes after 1 second, within the 2-second wait time.
  700. * };
  701. *
  702. * asyncActivity(); // The test will pass because the assertion is completed in time.
  703. * });
  704. * ```
  705. *
  706. * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing.
  707. * @since v22.2.0
  708. */
  709. plan(count: number, options?: TestContextPlanOptions): void;
  710. /**
  711. * If `shouldRunOnlyTests` is truthy, the test context will only run tests that
  712. * have the `only` option set. Otherwise, all tests are run. If Node.js was not
  713. * started with the `--test-only` command-line option, this function is a
  714. * no-op.
  715. *
  716. * ```js
  717. * test('top level test', (t) => {
  718. * // The test context can be set to run subtests with the 'only' option.
  719. * t.runOnly(true);
  720. * return Promise.all([
  721. * t.test('this subtest is now skipped'),
  722. * t.test('this subtest is run', { only: true }),
  723. * ]);
  724. * });
  725. * ```
  726. * @since v18.0.0, v16.17.0
  727. * @param shouldRunOnlyTests Whether or not to run `only` tests.
  728. */
  729. runOnly(shouldRunOnlyTests: boolean): void;
  730. /**
  731. * ```js
  732. * test('top level test', async (t) => {
  733. * await fetch('some/uri', { signal: t.signal });
  734. * });
  735. * ```
  736. * @since v18.7.0, v16.17.0
  737. */
  738. readonly signal: AbortSignal;
  739. /**
  740. * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does
  741. * not terminate execution of the test function. This function does not return a
  742. * value.
  743. *
  744. * ```js
  745. * test('top level test', (t) => {
  746. * // Make sure to return here as well if the test contains additional logic.
  747. * t.skip('this is skipped');
  748. * });
  749. * ```
  750. * @since v18.0.0, v16.17.0
  751. * @param message Optional skip message.
  752. */
  753. skip(message?: string): void;
  754. /**
  755. * This function adds a `TODO` directive to the test's output. If `message` is
  756. * provided, it is included in the output. Calling `todo()` does not terminate
  757. * execution of the test function. This function does not return a value.
  758. *
  759. * ```js
  760. * test('top level test', (t) => {
  761. * // This test is marked as `TODO`
  762. * t.todo('this is a todo');
  763. * });
  764. * ```
  765. * @since v18.0.0, v16.17.0
  766. * @param message Optional `TODO` message.
  767. */
  768. todo(message?: string): void;
  769. /**
  770. * This function is used to create subtests under the current test. This function behaves in
  771. * the same fashion as the top level {@link test} function.
  772. * @since v18.0.0
  773. * @param name The name of the test, which is displayed when reporting test results.
  774. * Defaults to the `name` property of `fn`, or `'<anonymous>'` if `fn` does not have a name.
  775. * @param options Configuration options for the test.
  776. * @param fn The function under test. This first argument to this function is a {@link TestContext} object.
  777. * If the test uses callbacks, the callback function is passed as the second argument.
  778. * @returns A {@link Promise} resolved with `undefined` once the test completes.
  779. */
  780. test: typeof test;
  781. /**
  782. * This method polls a `condition` function until that function either returns
  783. * successfully or the operation times out.
  784. * @since v22.14.0
  785. * @param condition An assertion function that is invoked
  786. * periodically until it completes successfully or the defined polling timeout
  787. * elapses. Successful completion is defined as not throwing or rejecting. This
  788. * function does not accept any arguments, and is allowed to return any value.
  789. * @param options An optional configuration object for the polling operation.
  790. * @returns Fulfilled with the value returned by `condition`.
  791. */
  792. waitFor<T>(condition: () => T, options?: TestContextWaitForOptions): Promise<Awaited<T>>;
  793. /**
  794. * Each test provides its own MockTracker instance.
  795. */
  796. readonly mock: MockTracker;
  797. }
  798. interface TestContextAssert extends
  799. Pick<
  800. typeof import("assert"),
  801. | "deepEqual"
  802. | "deepStrictEqual"
  803. | "doesNotMatch"
  804. | "doesNotReject"
  805. | "doesNotThrow"
  806. | "equal"
  807. | "fail"
  808. | "ifError"
  809. | "match"
  810. | "notDeepEqual"
  811. | "notDeepStrictEqual"
  812. | "notEqual"
  813. | "notStrictEqual"
  814. | "ok"
  815. | "partialDeepStrictEqual"
  816. | "rejects"
  817. | "strictEqual"
  818. | "throws"
  819. >
  820. {
  821. /**
  822. * This function serializes `value` and writes it to the file specified by `path`.
  823. *
  824. * ```js
  825. * test('snapshot test with default serialization', (t) => {
  826. * t.assert.fileSnapshot({ value1: 1, value2: 2 }, './snapshots/snapshot.json');
  827. * });
  828. * ```
  829. *
  830. * This function differs from `context.assert.snapshot()` in the following ways:
  831. *
  832. * * The snapshot file path is explicitly provided by the user.
  833. * * Each snapshot file is limited to a single snapshot value.
  834. * * No additional escaping is performed by the test runner.
  835. *
  836. * These differences allow snapshot files to better support features such as syntax
  837. * highlighting.
  838. * @since v22.14.0
  839. * @param value A value to serialize to a string. If Node.js was started with
  840. * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--test-update-snapshots)
  841. * flag, the serialized value is written to
  842. * `path`. Otherwise, the serialized value is compared to the contents of the
  843. * existing snapshot file.
  844. * @param path The file where the serialized `value` is written.
  845. * @param options Optional configuration options.
  846. */
  847. fileSnapshot(value: any, path: string, options?: AssertSnapshotOptions): void;
  848. /**
  849. * This function implements assertions for snapshot testing.
  850. * ```js
  851. * test('snapshot test with default serialization', (t) => {
  852. * t.assert.snapshot({ value1: 1, value2: 2 });
  853. * });
  854. *
  855. * test('snapshot test with custom serialization', (t) => {
  856. * t.assert.snapshot({ value3: 3, value4: 4 }, {
  857. * serializers: [(value) => JSON.stringify(value)]
  858. * });
  859. * });
  860. * ```
  861. * @since v22.3.0
  862. * @param value A value to serialize to a string. If Node.js was started with
  863. * the [`--test-update-snapshots`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--test-update-snapshots)
  864. * flag, the serialized value is written to
  865. * the snapshot file. Otherwise, the serialized value is compared to the
  866. * corresponding value in the existing snapshot file.
  867. */
  868. snapshot(value: any, options?: AssertSnapshotOptions): void;
  869. /**
  870. * A custom assertion function registered with `assert.register()`.
  871. */
  872. [name: string]: (...args: any[]) => void;
  873. }
  874. interface AssertSnapshotOptions {
  875. /**
  876. * An array of synchronous functions used to serialize `value` into a string.
  877. * `value` is passed as the only argument to the first serializer function.
  878. * The return value of each serializer is passed as input to the next serializer.
  879. * Once all serializers have run, the resulting value is coerced to a string.
  880. *
  881. * If no serializers are provided, the test runner's default serializers are used.
  882. */
  883. serializers?: ReadonlyArray<(value: any) => any> | undefined;
  884. }
  885. interface TestContextPlanOptions {
  886. /**
  887. * The wait time for the plan:
  888. * * If `true`, the plan waits indefinitely for all assertions and subtests to run.
  889. * * If `false`, the plan performs an immediate check after the test function completes,
  890. * without waiting for any pending assertions or subtests.
  891. * Any assertions or subtests that complete after this check will not be counted towards the plan.
  892. * * If a number, it specifies the maximum wait time in milliseconds
  893. * before timing out while waiting for expected assertions and subtests to be matched.
  894. * If the timeout is reached, the test will fail.
  895. * @default false
  896. */
  897. wait?: boolean | number | undefined;
  898. }
  899. interface TestContextWaitForOptions {
  900. /**
  901. * The number of milliseconds to wait after an unsuccessful
  902. * invocation of `condition` before trying again.
  903. * @default 50
  904. */
  905. interval?: number | undefined;
  906. /**
  907. * The poll timeout in milliseconds. If `condition` has not
  908. * succeeded by the time this elapses, an error occurs.
  909. * @default 1000
  910. */
  911. timeout?: number | undefined;
  912. }
  913. /**
  914. * An instance of `SuiteContext` is passed to each suite function in order to
  915. * interact with the test runner. However, the `SuiteContext` constructor is not
  916. * exposed as part of the API.
  917. * @since v18.7.0, v16.17.0
  918. */
  919. class SuiteContext {
  920. /**
  921. * The absolute path of the test file that created the current suite. If a test file imports
  922. * additional modules that generate suites, the imported suites will return the path of the root test file.
  923. * @since v22.6.0
  924. */
  925. readonly filePath: string | undefined;
  926. /**
  927. * The name of the suite.
  928. * @since v18.8.0, v16.18.0
  929. */
  930. readonly name: string;
  931. /**
  932. * Can be used to abort test subtasks when the test has been aborted.
  933. * @since v18.7.0, v16.17.0
  934. */
  935. readonly signal: AbortSignal;
  936. }
  937. interface TestOptions {
  938. /**
  939. * If a number is provided, then that many tests would run in parallel.
  940. * If truthy, it would run (number of cpu cores - 1) tests in parallel.
  941. * For subtests, it will be `Infinity` tests in parallel.
  942. * If falsy, it would only run one test at a time.
  943. * If unspecified, subtests inherit this value from their parent.
  944. * @default false
  945. */
  946. concurrency?: number | boolean | undefined;
  947. /**
  948. * If truthy, and the test context is configured to run `only` tests, then this test will be
  949. * run. Otherwise, the test is skipped.
  950. * @default false
  951. */
  952. only?: boolean | undefined;
  953. /**
  954. * Allows aborting an in-progress test.
  955. * @since v18.8.0
  956. */
  957. signal?: AbortSignal | undefined;
  958. /**
  959. * If truthy, the test is skipped. If a string is provided, that string is displayed in the
  960. * test results as the reason for skipping the test.
  961. * @default false
  962. */
  963. skip?: boolean | string | undefined;
  964. /**
  965. * A number of milliseconds the test will fail after. If unspecified, subtests inherit this
  966. * value from their parent.
  967. * @default Infinity
  968. * @since v18.7.0
  969. */
  970. timeout?: number | undefined;
  971. /**
  972. * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in
  973. * the test results as the reason why the test is `TODO`.
  974. * @default false
  975. */
  976. todo?: boolean | string | undefined;
  977. /**
  978. * The number of assertions and subtests expected to be run in the test.
  979. * If the number of assertions run in the test does not match the number
  980. * specified in the plan, the test will fail.
  981. * @default undefined
  982. * @since v22.2.0
  983. */
  984. plan?: number | undefined;
  985. }
  986. /**
  987. * This function creates a hook that runs before executing a suite.
  988. *
  989. * ```js
  990. * describe('tests', async () => {
  991. * before(() => console.log('about to run some test'));
  992. * it('is a subtest', () => {
  993. * assert.ok('some relevant assertion here');
  994. * });
  995. * });
  996. * ```
  997. * @since v18.8.0, v16.18.0
  998. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
  999. * @param options Configuration options for the hook.
  1000. */
  1001. function before(fn?: HookFn, options?: HookOptions): void;
  1002. /**
  1003. * This function creates a hook that runs after executing a suite.
  1004. *
  1005. * ```js
  1006. * describe('tests', async () => {
  1007. * after(() => console.log('finished running tests'));
  1008. * it('is a subtest', () => {
  1009. * assert.ok('some relevant assertion here');
  1010. * });
  1011. * });
  1012. * ```
  1013. * @since v18.8.0, v16.18.0
  1014. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
  1015. * @param options Configuration options for the hook.
  1016. */
  1017. function after(fn?: HookFn, options?: HookOptions): void;
  1018. /**
  1019. * This function creates a hook that runs before each test in the current suite.
  1020. *
  1021. * ```js
  1022. * describe('tests', async () => {
  1023. * beforeEach(() => console.log('about to run a test'));
  1024. * it('is a subtest', () => {
  1025. * assert.ok('some relevant assertion here');
  1026. * });
  1027. * });
  1028. * ```
  1029. * @since v18.8.0, v16.18.0
  1030. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
  1031. * @param options Configuration options for the hook.
  1032. */
  1033. function beforeEach(fn?: HookFn, options?: HookOptions): void;
  1034. /**
  1035. * This function creates a hook that runs after each test in the current suite.
  1036. * The `afterEach()` hook is run even if the test fails.
  1037. *
  1038. * ```js
  1039. * describe('tests', async () => {
  1040. * afterEach(() => console.log('finished running a test'));
  1041. * it('is a subtest', () => {
  1042. * assert.ok('some relevant assertion here');
  1043. * });
  1044. * });
  1045. * ```
  1046. * @since v18.8.0, v16.18.0
  1047. * @param fn The hook function. If the hook uses callbacks, the callback function is passed as the second argument.
  1048. * @param options Configuration options for the hook.
  1049. */
  1050. function afterEach(fn?: HookFn, options?: HookOptions): void;
  1051. /**
  1052. * The hook function. The first argument is the context in which the hook is called.
  1053. * If the hook uses callbacks, the callback function is passed as the second argument.
  1054. */
  1055. type HookFn = (c: TestContext | SuiteContext, done: (result?: any) => void) => any;
  1056. /**
  1057. * The hook function. The first argument is a `TestContext` object.
  1058. * If the hook uses callbacks, the callback function is passed as the second argument.
  1059. */
  1060. type TestContextHookFn = (t: TestContext, done: (result?: any) => void) => any;
  1061. /**
  1062. * Configuration options for hooks.
  1063. * @since v18.8.0
  1064. */
  1065. interface HookOptions {
  1066. /**
  1067. * Allows aborting an in-progress hook.
  1068. */
  1069. signal?: AbortSignal | undefined;
  1070. /**
  1071. * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this
  1072. * value from their parent.
  1073. * @default Infinity
  1074. */
  1075. timeout?: number | undefined;
  1076. }
  1077. interface MockFunctionOptions {
  1078. /**
  1079. * The number of times that the mock will use the behavior of `implementation`.
  1080. * Once the mock function has been called `times` times,
  1081. * it will automatically restore the behavior of `original`.
  1082. * This value must be an integer greater than zero.
  1083. * @default Infinity
  1084. */
  1085. times?: number | undefined;
  1086. }
  1087. interface MockMethodOptions extends MockFunctionOptions {
  1088. /**
  1089. * If `true`, `object[methodName]` is treated as a getter.
  1090. * This option cannot be used with the `setter` option.
  1091. */
  1092. getter?: boolean | undefined;
  1093. /**
  1094. * If `true`, `object[methodName]` is treated as a setter.
  1095. * This option cannot be used with the `getter` option.
  1096. */
  1097. setter?: boolean | undefined;
  1098. }
  1099. type Mock<F extends Function> = F & {
  1100. mock: MockFunctionContext<F>;
  1101. };
  1102. type NoOpFunction = (...args: any[]) => undefined;
  1103. type FunctionPropertyNames<T> = {
  1104. [K in keyof T]: T[K] extends Function ? K : never;
  1105. }[keyof T];
  1106. interface MockModuleOptions {
  1107. /**
  1108. * If false, each call to `require()` or `import()` generates a new mock module.
  1109. * If true, subsequent calls will return the same module mock, and the mock module is inserted into the CommonJS cache.
  1110. * @default false
  1111. */
  1112. cache?: boolean | undefined;
  1113. /**
  1114. * The value to use as the mocked module's default export.
  1115. *
  1116. * If this value is not provided, ESM mocks do not include a default export.
  1117. * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`.
  1118. * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`.
  1119. */
  1120. defaultExport?: any;
  1121. /**
  1122. * An object whose keys and values are used to create the named exports of the mock module.
  1123. *
  1124. * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`.
  1125. * Therefore, if a mock is created with both named exports and a non-object default export,
  1126. * the mock will throw an exception when used as a CJS or builtin module.
  1127. */
  1128. namedExports?: object | undefined;
  1129. }
  1130. /**
  1131. * The `MockTracker` class is used to manage mocking functionality. The test runner
  1132. * module provides a top level `mock` export which is a `MockTracker` instance.
  1133. * Each test also provides its own `MockTracker` instance via the test context's `mock` property.
  1134. * @since v19.1.0, v18.13.0
  1135. */
  1136. class MockTracker {
  1137. /**
  1138. * This function is used to create a mock function.
  1139. *
  1140. * The following example creates a mock function that increments a counter by one
  1141. * on each invocation. The `times` option is used to modify the mock behavior such
  1142. * that the first two invocations add two to the counter instead of one.
  1143. *
  1144. * ```js
  1145. * test('mocks a counting function', (t) => {
  1146. * let cnt = 0;
  1147. *
  1148. * function addOne() {
  1149. * cnt++;
  1150. * return cnt;
  1151. * }
  1152. *
  1153. * function addTwo() {
  1154. * cnt += 2;
  1155. * return cnt;
  1156. * }
  1157. *
  1158. * const fn = t.mock.fn(addOne, addTwo, { times: 2 });
  1159. *
  1160. * assert.strictEqual(fn(), 2);
  1161. * assert.strictEqual(fn(), 4);
  1162. * assert.strictEqual(fn(), 5);
  1163. * assert.strictEqual(fn(), 6);
  1164. * });
  1165. * ```
  1166. * @since v19.1.0, v18.13.0
  1167. * @param original An optional function to create a mock on.
  1168. * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and
  1169. * then restore the behavior of `original`.
  1170. * @param options Optional configuration options for the mock function.
  1171. * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the
  1172. * behavior of the mocked function.
  1173. */
  1174. fn<F extends Function = NoOpFunction>(original?: F, options?: MockFunctionOptions): Mock<F>;
  1175. fn<F extends Function = NoOpFunction, Implementation extends Function = F>(
  1176. original?: F,
  1177. implementation?: Implementation,
  1178. options?: MockFunctionOptions,
  1179. ): Mock<F | Implementation>;
  1180. /**
  1181. * This function is used to create a mock on an existing object method. The
  1182. * following example demonstrates how a mock is created on an existing object
  1183. * method.
  1184. *
  1185. * ```js
  1186. * test('spies on an object method', (t) => {
  1187. * const number = {
  1188. * value: 5,
  1189. * subtract(a) {
  1190. * return this.value - a;
  1191. * },
  1192. * };
  1193. *
  1194. * t.mock.method(number, 'subtract');
  1195. * assert.strictEqual(number.subtract.mock.calls.length, 0);
  1196. * assert.strictEqual(number.subtract(3), 2);
  1197. * assert.strictEqual(number.subtract.mock.calls.length, 1);
  1198. *
  1199. * const call = number.subtract.mock.calls[0];
  1200. *
  1201. * assert.deepStrictEqual(call.arguments, [3]);
  1202. * assert.strictEqual(call.result, 2);
  1203. * assert.strictEqual(call.error, undefined);
  1204. * assert.strictEqual(call.target, undefined);
  1205. * assert.strictEqual(call.this, number);
  1206. * });
  1207. * ```
  1208. * @since v19.1.0, v18.13.0
  1209. * @param object The object whose method is being mocked.
  1210. * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown.
  1211. * @param implementation An optional function used as the mock implementation for `object[methodName]`.
  1212. * @param options Optional configuration options for the mock method.
  1213. * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the
  1214. * behavior of the mocked method.
  1215. */
  1216. method<
  1217. MockedObject extends object,
  1218. MethodName extends FunctionPropertyNames<MockedObject>,
  1219. >(
  1220. object: MockedObject,
  1221. methodName: MethodName,
  1222. options?: MockFunctionOptions,
  1223. ): MockedObject[MethodName] extends Function ? Mock<MockedObject[MethodName]>
  1224. : never;
  1225. method<
  1226. MockedObject extends object,
  1227. MethodName extends FunctionPropertyNames<MockedObject>,
  1228. Implementation extends Function,
  1229. >(
  1230. object: MockedObject,
  1231. methodName: MethodName,
  1232. implementation: Implementation,
  1233. options?: MockFunctionOptions,
  1234. ): MockedObject[MethodName] extends Function ? Mock<MockedObject[MethodName] | Implementation>
  1235. : never;
  1236. method<MockedObject extends object>(
  1237. object: MockedObject,
  1238. methodName: keyof MockedObject,
  1239. options: MockMethodOptions,
  1240. ): Mock<Function>;
  1241. method<MockedObject extends object>(
  1242. object: MockedObject,
  1243. methodName: keyof MockedObject,
  1244. implementation: Function,
  1245. options: MockMethodOptions,
  1246. ): Mock<Function>;
  1247. /**
  1248. * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`.
  1249. * @since v19.3.0, v18.13.0
  1250. */
  1251. getter<
  1252. MockedObject extends object,
  1253. MethodName extends keyof MockedObject,
  1254. >(
  1255. object: MockedObject,
  1256. methodName: MethodName,
  1257. options?: MockFunctionOptions,
  1258. ): Mock<() => MockedObject[MethodName]>;
  1259. getter<
  1260. MockedObject extends object,
  1261. MethodName extends keyof MockedObject,
  1262. Implementation extends Function,
  1263. >(
  1264. object: MockedObject,
  1265. methodName: MethodName,
  1266. implementation?: Implementation,
  1267. options?: MockFunctionOptions,
  1268. ): Mock<(() => MockedObject[MethodName]) | Implementation>;
  1269. /**
  1270. * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`.
  1271. * @since v19.3.0, v18.13.0
  1272. */
  1273. setter<
  1274. MockedObject extends object,
  1275. MethodName extends keyof MockedObject,
  1276. >(
  1277. object: MockedObject,
  1278. methodName: MethodName,
  1279. options?: MockFunctionOptions,
  1280. ): Mock<(value: MockedObject[MethodName]) => void>;
  1281. setter<
  1282. MockedObject extends object,
  1283. MethodName extends keyof MockedObject,
  1284. Implementation extends Function,
  1285. >(
  1286. object: MockedObject,
  1287. methodName: MethodName,
  1288. implementation?: Implementation,
  1289. options?: MockFunctionOptions,
  1290. ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>;
  1291. /**
  1292. * This function is used to mock the exports of ECMAScript modules, CommonJS modules, and Node.js builtin modules.
  1293. * Any references to the original module prior to mocking are not impacted.
  1294. *
  1295. * Only available through the [--experimental-test-module-mocks](https://nodejs.org/api/cli.html#--experimental-test-module-mocks) flag.
  1296. * @since v22.3.0
  1297. * @experimental
  1298. * @param specifier A string identifying the module to mock.
  1299. * @param options Optional configuration options for the mock module.
  1300. */
  1301. module(specifier: string, options?: MockModuleOptions): MockModuleContext;
  1302. /**
  1303. * This function restores the default behavior of all mocks that were previously
  1304. * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be
  1305. * used to reset their behavior or
  1306. * otherwise interact with them.
  1307. *
  1308. * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this
  1309. * function manually is recommended.
  1310. * @since v19.1.0, v18.13.0
  1311. */
  1312. reset(): void;
  1313. /**
  1314. * This function restores the default behavior of all mocks that were previously
  1315. * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does
  1316. * not disassociate the mocks from the `MockTracker` instance.
  1317. * @since v19.1.0, v18.13.0
  1318. */
  1319. restoreAll(): void;
  1320. timers: MockTimers;
  1321. }
  1322. const mock: MockTracker;
  1323. interface MockFunctionCall<
  1324. F extends Function,
  1325. ReturnType = F extends (...args: any) => infer T ? T
  1326. : F extends abstract new(...args: any) => infer T ? T
  1327. : unknown,
  1328. Args = F extends (...args: infer Y) => any ? Y
  1329. : F extends abstract new(...args: infer Y) => any ? Y
  1330. : unknown[],
  1331. > {
  1332. /**
  1333. * An array of the arguments passed to the mock function.
  1334. */
  1335. arguments: Args;
  1336. /**
  1337. * If the mocked function threw then this property contains the thrown value.
  1338. */
  1339. error: unknown | undefined;
  1340. /**
  1341. * The value returned by the mocked function.
  1342. *
  1343. * If the mocked function threw, it will be `undefined`.
  1344. */
  1345. result: ReturnType | undefined;
  1346. /**
  1347. * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation.
  1348. */
  1349. stack: Error;
  1350. /**
  1351. * If the mocked function is a constructor, this field contains the class being constructed.
  1352. * Otherwise this will be `undefined`.
  1353. */
  1354. target: F extends abstract new(...args: any) => any ? F : undefined;
  1355. /**
  1356. * The mocked function's `this` value.
  1357. */
  1358. this: unknown;
  1359. }
  1360. /**
  1361. * The `MockFunctionContext` class is used to inspect or manipulate the behavior of
  1362. * mocks created via the `MockTracker` APIs.
  1363. * @since v19.1.0, v18.13.0
  1364. */
  1365. class MockFunctionContext<F extends Function> {
  1366. /**
  1367. * A getter that returns a copy of the internal array used to track calls to the
  1368. * mock. Each entry in the array is an object with the following properties.
  1369. * @since v19.1.0, v18.13.0
  1370. */
  1371. readonly calls: Array<MockFunctionCall<F>>;
  1372. /**
  1373. * This function returns the number of times that this mock has been invoked. This
  1374. * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array.
  1375. * @since v19.1.0, v18.13.0
  1376. * @return The number of times that this mock has been invoked.
  1377. */
  1378. callCount(): number;
  1379. /**
  1380. * This function is used to change the behavior of an existing mock.
  1381. *
  1382. * The following example creates a mock function using `t.mock.fn()`, calls the
  1383. * mock function, and then changes the mock implementation to a different function.
  1384. *
  1385. * ```js
  1386. * test('changes a mock behavior', (t) => {
  1387. * let cnt = 0;
  1388. *
  1389. * function addOne() {
  1390. * cnt++;
  1391. * return cnt;
  1392. * }
  1393. *
  1394. * function addTwo() {
  1395. * cnt += 2;
  1396. * return cnt;
  1397. * }
  1398. *
  1399. * const fn = t.mock.fn(addOne);
  1400. *
  1401. * assert.strictEqual(fn(), 1);
  1402. * fn.mock.mockImplementation(addTwo);
  1403. * assert.strictEqual(fn(), 3);
  1404. * assert.strictEqual(fn(), 5);
  1405. * });
  1406. * ```
  1407. * @since v19.1.0, v18.13.0
  1408. * @param implementation The function to be used as the mock's new implementation.
  1409. */
  1410. mockImplementation(implementation: F): void;
  1411. /**
  1412. * This function is used to change the behavior of an existing mock for a single
  1413. * invocation. Once invocation `onCall` has occurred, the mock will revert to
  1414. * whatever behavior it would have used had `mockImplementationOnce()` not been
  1415. * called.
  1416. *
  1417. * The following example creates a mock function using `t.mock.fn()`, calls the
  1418. * mock function, changes the mock implementation to a different function for the
  1419. * next invocation, and then resumes its previous behavior.
  1420. *
  1421. * ```js
  1422. * test('changes a mock behavior once', (t) => {
  1423. * let cnt = 0;
  1424. *
  1425. * function addOne() {
  1426. * cnt++;
  1427. * return cnt;
  1428. * }
  1429. *
  1430. * function addTwo() {
  1431. * cnt += 2;
  1432. * return cnt;
  1433. * }
  1434. *
  1435. * const fn = t.mock.fn(addOne);
  1436. *
  1437. * assert.strictEqual(fn(), 1);
  1438. * fn.mock.mockImplementationOnce(addTwo);
  1439. * assert.strictEqual(fn(), 3);
  1440. * assert.strictEqual(fn(), 4);
  1441. * });
  1442. * ```
  1443. * @since v19.1.0, v18.13.0
  1444. * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`.
  1445. * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown.
  1446. */
  1447. mockImplementationOnce(implementation: F, onCall?: number): void;
  1448. /**
  1449. * Resets the call history of the mock function.
  1450. * @since v19.3.0, v18.13.0
  1451. */
  1452. resetCalls(): void;
  1453. /**
  1454. * Resets the implementation of the mock function to its original behavior. The
  1455. * mock can still be used after calling this function.
  1456. * @since v19.1.0, v18.13.0
  1457. */
  1458. restore(): void;
  1459. }
  1460. /**
  1461. * @since v22.3.0
  1462. * @experimental
  1463. */
  1464. class MockModuleContext {
  1465. /**
  1466. * Resets the implementation of the mock module.
  1467. * @since v22.3.0
  1468. */
  1469. restore(): void;
  1470. }
  1471. type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date";
  1472. interface MockTimersOptions {
  1473. apis: Timer[];
  1474. now?: number | Date | undefined;
  1475. }
  1476. /**
  1477. * Mocking timers is a technique commonly used in software testing to simulate and
  1478. * control the behavior of timers, such as `setInterval` and `setTimeout`,
  1479. * without actually waiting for the specified time intervals.
  1480. *
  1481. * The MockTimers API also allows for mocking of the `Date` constructor and
  1482. * `setImmediate`/`clearImmediate` functions.
  1483. *
  1484. * The `MockTracker` provides a top-level `timers` export
  1485. * which is a `MockTimers` instance.
  1486. * @since v20.4.0
  1487. * @experimental
  1488. */
  1489. class MockTimers {
  1490. /**
  1491. * Enables timer mocking for the specified timers.
  1492. *
  1493. * **Note:** When you enable mocking for a specific timer, its associated
  1494. * clear function will also be implicitly mocked.
  1495. *
  1496. * **Note:** Mocking `Date` will affect the behavior of the mocked timers
  1497. * as they use the same internal clock.
  1498. *
  1499. * Example usage without setting initial time:
  1500. *
  1501. * ```js
  1502. * import { mock } from 'node:test';
  1503. * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 });
  1504. * ```
  1505. *
  1506. * The above example enables mocking for the `Date` constructor, `setInterval` timer and
  1507. * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`,
  1508. * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked.
  1509. *
  1510. * Example usage with initial time set
  1511. *
  1512. * ```js
  1513. * import { mock } from 'node:test';
  1514. * mock.timers.enable({ apis: ['Date'], now: 1000 });
  1515. * ```
  1516. *
  1517. * Example usage with initial Date object as time set
  1518. *
  1519. * ```js
  1520. * import { mock } from 'node:test';
  1521. * mock.timers.enable({ apis: ['Date'], now: new Date() });
  1522. * ```
  1523. *
  1524. * Alternatively, if you call `mock.timers.enable()` without any parameters:
  1525. *
  1526. * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`)
  1527. * will be mocked.
  1528. *
  1529. * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`,
  1530. * and `globalThis` will be mocked.
  1531. * The `Date` constructor from `globalThis` will be mocked.
  1532. *
  1533. * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can
  1534. * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date
  1535. * object. It can either be a positive integer, or another Date object.
  1536. * @since v20.4.0
  1537. */
  1538. enable(options?: MockTimersOptions): void;
  1539. /**
  1540. * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer.
  1541. * Note: This method will execute any mocked timers that are in the past from the new time.
  1542. * In the below example we are setting a new time for the mocked date.
  1543. * ```js
  1544. * import assert from 'node:assert';
  1545. * import { test } from 'node:test';
  1546. * test('sets the time of a date object', (context) => {
  1547. * // Optionally choose what to mock
  1548. * context.mock.timers.enable({ apis: ['Date'], now: 100 });
  1549. * assert.strictEqual(Date.now(), 100);
  1550. * // Advance in time will also advance the date
  1551. * context.mock.timers.setTime(1000);
  1552. * context.mock.timers.tick(200);
  1553. * assert.strictEqual(Date.now(), 1200);
  1554. * });
  1555. * ```
  1556. */
  1557. setTime(time: number): void;
  1558. /**
  1559. * This function restores the default behavior of all mocks that were previously
  1560. * created by this `MockTimers` instance and disassociates the mocks
  1561. * from the `MockTracker` instance.
  1562. *
  1563. * **Note:** After each test completes, this function is called on
  1564. * the test context's `MockTracker`.
  1565. *
  1566. * ```js
  1567. * import { mock } from 'node:test';
  1568. * mock.timers.reset();
  1569. * ```
  1570. * @since v20.4.0
  1571. */
  1572. reset(): void;
  1573. /**
  1574. * Advances time for all mocked timers.
  1575. *
  1576. * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts
  1577. * only positive numbers. In Node.js, `setTimeout` with negative numbers is
  1578. * only supported for web compatibility reasons.
  1579. *
  1580. * The following example mocks a `setTimeout` function and
  1581. * by using `.tick` advances in
  1582. * time triggering all pending timers.
  1583. *
  1584. * ```js
  1585. * import assert from 'node:assert';
  1586. * import { test } from 'node:test';
  1587. *
  1588. * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  1589. * const fn = context.mock.fn();
  1590. *
  1591. * context.mock.timers.enable({ apis: ['setTimeout'] });
  1592. *
  1593. * setTimeout(fn, 9999);
  1594. *
  1595. * assert.strictEqual(fn.mock.callCount(), 0);
  1596. *
  1597. * // Advance in time
  1598. * context.mock.timers.tick(9999);
  1599. *
  1600. * assert.strictEqual(fn.mock.callCount(), 1);
  1601. * });
  1602. * ```
  1603. *
  1604. * Alternativelly, the `.tick` function can be called many times
  1605. *
  1606. * ```js
  1607. * import assert from 'node:assert';
  1608. * import { test } from 'node:test';
  1609. *
  1610. * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  1611. * const fn = context.mock.fn();
  1612. * context.mock.timers.enable({ apis: ['setTimeout'] });
  1613. * const nineSecs = 9000;
  1614. * setTimeout(fn, nineSecs);
  1615. *
  1616. * const twoSeconds = 3000;
  1617. * context.mock.timers.tick(twoSeconds);
  1618. * context.mock.timers.tick(twoSeconds);
  1619. * context.mock.timers.tick(twoSeconds);
  1620. *
  1621. * assert.strictEqual(fn.mock.callCount(), 1);
  1622. * });
  1623. * ```
  1624. *
  1625. * Advancing time using `.tick` will also advance the time for any `Date` object
  1626. * created after the mock was enabled (if `Date` was also set to be mocked).
  1627. *
  1628. * ```js
  1629. * import assert from 'node:assert';
  1630. * import { test } from 'node:test';
  1631. *
  1632. * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => {
  1633. * const fn = context.mock.fn();
  1634. *
  1635. * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
  1636. * setTimeout(fn, 9999);
  1637. *
  1638. * assert.strictEqual(fn.mock.callCount(), 0);
  1639. * assert.strictEqual(Date.now(), 0);
  1640. *
  1641. * // Advance in time
  1642. * context.mock.timers.tick(9999);
  1643. * assert.strictEqual(fn.mock.callCount(), 1);
  1644. * assert.strictEqual(Date.now(), 9999);
  1645. * });
  1646. * ```
  1647. * @since v20.4.0
  1648. */
  1649. tick(milliseconds: number): void;
  1650. /**
  1651. * Triggers all pending mocked timers immediately. If the `Date` object is also
  1652. * mocked, it will also advance the `Date` object to the furthest timer's time.
  1653. *
  1654. * The example below triggers all pending timers immediately,
  1655. * causing them to execute without any delay.
  1656. *
  1657. * ```js
  1658. * import assert from 'node:assert';
  1659. * import { test } from 'node:test';
  1660. *
  1661. * test('runAll functions following the given order', (context) => {
  1662. * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] });
  1663. * const results = [];
  1664. * setTimeout(() => results.push(1), 9999);
  1665. *
  1666. * // Notice that if both timers have the same timeout,
  1667. * // the order of execution is guaranteed
  1668. * setTimeout(() => results.push(3), 8888);
  1669. * setTimeout(() => results.push(2), 8888);
  1670. *
  1671. * assert.deepStrictEqual(results, []);
  1672. *
  1673. * context.mock.timers.runAll();
  1674. * assert.deepStrictEqual(results, [3, 2, 1]);
  1675. * // The Date object is also advanced to the furthest timer's time
  1676. * assert.strictEqual(Date.now(), 9999);
  1677. * });
  1678. * ```
  1679. *
  1680. * **Note:** The `runAll()` function is specifically designed for
  1681. * triggering timers in the context of timer mocking.
  1682. * It does not have any effect on real-time system
  1683. * clocks or actual timers outside of the mocking environment.
  1684. * @since v20.4.0
  1685. */
  1686. runAll(): void;
  1687. /**
  1688. * Calls {@link MockTimers.reset()}.
  1689. */
  1690. [Symbol.dispose](): void;
  1691. }
  1692. /**
  1693. * An object whose methods are used to configure available assertions on the
  1694. * `TestContext` objects in the current process. The methods from `node:assert`
  1695. * and snapshot testing functions are available by default.
  1696. *
  1697. * It is possible to apply the same configuration to all files by placing common
  1698. * configuration code in a module
  1699. * preloaded with `--require` or `--import`.
  1700. * @since v22.14.0
  1701. */
  1702. namespace assert {
  1703. /**
  1704. * Defines a new assertion function with the provided name and function. If an
  1705. * assertion already exists with the same name, it is overwritten.
  1706. * @since v22.14.0
  1707. */
  1708. function register(name: string, fn: (this: TestContext, ...args: any[]) => void): void;
  1709. }
  1710. /**
  1711. * @since v22.3.0
  1712. */
  1713. namespace snapshot {
  1714. /**
  1715. * This function is used to customize the default serialization mechanism used by the test runner.
  1716. *
  1717. * By default, the test runner performs serialization by calling `JSON.stringify(value, null, 2)` on the provided value.
  1718. * `JSON.stringify()` does have limitations regarding circular structures and supported data types.
  1719. * If a more robust serialization mechanism is required, this function should be used to specify a list of custom serializers.
  1720. *
  1721. * Serializers are called in order, with the output of the previous serializer passed as input to the next.
  1722. * The final result must be a string value.
  1723. * @since v22.3.0
  1724. * @param serializers An array of synchronous functions used as the default serializers for snapshot tests.
  1725. */
  1726. function setDefaultSnapshotSerializers(serializers: ReadonlyArray<(value: any) => any>): void;
  1727. /**
  1728. * This function is used to set a custom resolver for the location of the snapshot file used for snapshot testing.
  1729. * By default, the snapshot filename is the same as the entry point filename with `.snapshot` appended.
  1730. * @since v22.3.0
  1731. * @param fn A function used to compute the location of the snapshot file.
  1732. * The function receives the path of the test file as its only argument. If the
  1733. * test is not associated with a file (for example in the REPL), the input is
  1734. * undefined. `fn()` must return a string specifying the location of the snapshot file.
  1735. */
  1736. function setResolveSnapshotPath(fn: (path: string | undefined) => string): void;
  1737. }
  1738. export {
  1739. after,
  1740. afterEach,
  1741. assert,
  1742. before,
  1743. beforeEach,
  1744. describe,
  1745. it,
  1746. Mock,
  1747. mock,
  1748. only,
  1749. run,
  1750. skip,
  1751. snapshot,
  1752. suite,
  1753. SuiteContext,
  1754. test,
  1755. test as default,
  1756. TestContext,
  1757. todo,
  1758. };
  1759. }
  1760. interface TestError extends Error {
  1761. cause: Error;
  1762. }
  1763. interface TestLocationInfo {
  1764. /**
  1765. * The column number where the test is defined, or
  1766. * `undefined` if the test was run through the REPL.
  1767. */
  1768. column?: number;
  1769. /**
  1770. * The path of the test file, `undefined` if test was run through the REPL.
  1771. */
  1772. file?: string;
  1773. /**
  1774. * The line number where the test is defined, or `undefined` if the test was run through the REPL.
  1775. */
  1776. line?: number;
  1777. }
  1778. interface DiagnosticData extends TestLocationInfo {
  1779. /**
  1780. * The diagnostic message.
  1781. */
  1782. message: string;
  1783. /**
  1784. * The nesting level of the test.
  1785. */
  1786. nesting: number;
  1787. }
  1788. interface TestCoverage {
  1789. /**
  1790. * An object containing the coverage report.
  1791. */
  1792. summary: {
  1793. /**
  1794. * An array of coverage reports for individual files.
  1795. */
  1796. files: Array<{
  1797. /**
  1798. * The absolute path of the file.
  1799. */
  1800. path: string;
  1801. /**
  1802. * The total number of lines.
  1803. */
  1804. totalLineCount: number;
  1805. /**
  1806. * The total number of branches.
  1807. */
  1808. totalBranchCount: number;
  1809. /**
  1810. * The total number of functions.
  1811. */
  1812. totalFunctionCount: number;
  1813. /**
  1814. * The number of covered lines.
  1815. */
  1816. coveredLineCount: number;
  1817. /**
  1818. * The number of covered branches.
  1819. */
  1820. coveredBranchCount: number;
  1821. /**
  1822. * The number of covered functions.
  1823. */
  1824. coveredFunctionCount: number;
  1825. /**
  1826. * The percentage of lines covered.
  1827. */
  1828. coveredLinePercent: number;
  1829. /**
  1830. * The percentage of branches covered.
  1831. */
  1832. coveredBranchPercent: number;
  1833. /**
  1834. * The percentage of functions covered.
  1835. */
  1836. coveredFunctionPercent: number;
  1837. /**
  1838. * An array of functions representing function coverage.
  1839. */
  1840. functions: Array<{
  1841. /**
  1842. * The name of the function.
  1843. */
  1844. name: string;
  1845. /**
  1846. * The line number where the function is defined.
  1847. */
  1848. line: number;
  1849. /**
  1850. * The number of times the function was called.
  1851. */
  1852. count: number;
  1853. }>;
  1854. /**
  1855. * An array of branches representing branch coverage.
  1856. */
  1857. branches: Array<{
  1858. /**
  1859. * The line number where the branch is defined.
  1860. */
  1861. line: number;
  1862. /**
  1863. * The number of times the branch was taken.
  1864. */
  1865. count: number;
  1866. }>;
  1867. /**
  1868. * An array of lines representing line numbers and the number of times they were covered.
  1869. */
  1870. lines: Array<{
  1871. /**
  1872. * The line number.
  1873. */
  1874. line: number;
  1875. /**
  1876. * The number of times the line was covered.
  1877. */
  1878. count: number;
  1879. }>;
  1880. }>;
  1881. /**
  1882. * An object containing whether or not the coverage for
  1883. * each coverage type.
  1884. * @since v22.9.0
  1885. */
  1886. thresholds: {
  1887. /**
  1888. * The function coverage threshold.
  1889. */
  1890. function: number;
  1891. /**
  1892. * The branch coverage threshold.
  1893. */
  1894. branch: number;
  1895. /**
  1896. * The line coverage threshold.
  1897. */
  1898. line: number;
  1899. };
  1900. /**
  1901. * An object containing a summary of coverage for all files.
  1902. */
  1903. totals: {
  1904. /**
  1905. * The total number of lines.
  1906. */
  1907. totalLineCount: number;
  1908. /**
  1909. * The total number of branches.
  1910. */
  1911. totalBranchCount: number;
  1912. /**
  1913. * The total number of functions.
  1914. */
  1915. totalFunctionCount: number;
  1916. /**
  1917. * The number of covered lines.
  1918. */
  1919. coveredLineCount: number;
  1920. /**
  1921. * The number of covered branches.
  1922. */
  1923. coveredBranchCount: number;
  1924. /**
  1925. * The number of covered functions.
  1926. */
  1927. coveredFunctionCount: number;
  1928. /**
  1929. * The percentage of lines covered.
  1930. */
  1931. coveredLinePercent: number;
  1932. /**
  1933. * The percentage of branches covered.
  1934. */
  1935. coveredBranchPercent: number;
  1936. /**
  1937. * The percentage of functions covered.
  1938. */
  1939. coveredFunctionPercent: number;
  1940. };
  1941. /**
  1942. * The working directory when code coverage began. This
  1943. * is useful for displaying relative path names in case
  1944. * the tests changed the working directory of the Node.js process.
  1945. */
  1946. workingDirectory: string;
  1947. };
  1948. /**
  1949. * The nesting level of the test.
  1950. */
  1951. nesting: number;
  1952. }
  1953. interface TestComplete extends TestLocationInfo {
  1954. /**
  1955. * Additional execution metadata.
  1956. */
  1957. details: {
  1958. /**
  1959. * Whether the test passed or not.
  1960. */
  1961. passed: boolean;
  1962. /**
  1963. * The duration of the test in milliseconds.
  1964. */
  1965. duration_ms: number;
  1966. /**
  1967. * An error wrapping the error thrown by the test if it did not pass.
  1968. */
  1969. error?: TestError;
  1970. /**
  1971. * The type of the test, used to denote whether this is a suite.
  1972. */
  1973. type?: "suite";
  1974. };
  1975. /**
  1976. * The test name.
  1977. */
  1978. name: string;
  1979. /**
  1980. * The nesting level of the test.
  1981. */
  1982. nesting: number;
  1983. /**
  1984. * The ordinal number of the test.
  1985. */
  1986. testNumber: number;
  1987. /**
  1988. * Present if `context.todo` is called.
  1989. */
  1990. todo?: string | boolean;
  1991. /**
  1992. * Present if `context.skip` is called.
  1993. */
  1994. skip?: string | boolean;
  1995. }
  1996. interface TestDequeue extends TestLocationInfo {
  1997. /**
  1998. * The test name.
  1999. */
  2000. name: string;
  2001. /**
  2002. * The nesting level of the test.
  2003. */
  2004. nesting: number;
  2005. /**
  2006. * The test type. Either `'suite'` or `'test'`.
  2007. * @since v22.15.0
  2008. */
  2009. type: "suite" | "test";
  2010. }
  2011. interface TestEnqueue extends TestLocationInfo {
  2012. /**
  2013. * The test name.
  2014. */
  2015. name: string;
  2016. /**
  2017. * The nesting level of the test.
  2018. */
  2019. nesting: number;
  2020. /**
  2021. * The test type. Either `'suite'` or `'test'`.
  2022. * @since v22.15.0
  2023. */
  2024. type: "suite" | "test";
  2025. }
  2026. interface TestFail extends TestLocationInfo {
  2027. /**
  2028. * Additional execution metadata.
  2029. */
  2030. details: {
  2031. /**
  2032. * The duration of the test in milliseconds.
  2033. */
  2034. duration_ms: number;
  2035. /**
  2036. * An error wrapping the error thrown by the test.
  2037. */
  2038. error: TestError;
  2039. /**
  2040. * The type of the test, used to denote whether this is a suite.
  2041. * @since v20.0.0, v19.9.0, v18.17.0
  2042. */
  2043. type?: "suite";
  2044. };
  2045. /**
  2046. * The test name.
  2047. */
  2048. name: string;
  2049. /**
  2050. * The nesting level of the test.
  2051. */
  2052. nesting: number;
  2053. /**
  2054. * The ordinal number of the test.
  2055. */
  2056. testNumber: number;
  2057. /**
  2058. * Present if `context.todo` is called.
  2059. */
  2060. todo?: string | boolean;
  2061. /**
  2062. * Present if `context.skip` is called.
  2063. */
  2064. skip?: string | boolean;
  2065. }
  2066. interface TestPass extends TestLocationInfo {
  2067. /**
  2068. * Additional execution metadata.
  2069. */
  2070. details: {
  2071. /**
  2072. * The duration of the test in milliseconds.
  2073. */
  2074. duration_ms: number;
  2075. /**
  2076. * The type of the test, used to denote whether this is a suite.
  2077. * @since 20.0.0, 19.9.0, 18.17.0
  2078. */
  2079. type?: "suite";
  2080. };
  2081. /**
  2082. * The test name.
  2083. */
  2084. name: string;
  2085. /**
  2086. * The nesting level of the test.
  2087. */
  2088. nesting: number;
  2089. /**
  2090. * The ordinal number of the test.
  2091. */
  2092. testNumber: number;
  2093. /**
  2094. * Present if `context.todo` is called.
  2095. */
  2096. todo?: string | boolean;
  2097. /**
  2098. * Present if `context.skip` is called.
  2099. */
  2100. skip?: string | boolean;
  2101. }
  2102. interface TestPlan extends TestLocationInfo {
  2103. /**
  2104. * The nesting level of the test.
  2105. */
  2106. nesting: number;
  2107. /**
  2108. * The number of subtests that have ran.
  2109. */
  2110. count: number;
  2111. }
  2112. interface TestStart extends TestLocationInfo {
  2113. /**
  2114. * The test name.
  2115. */
  2116. name: string;
  2117. /**
  2118. * The nesting level of the test.
  2119. */
  2120. nesting: number;
  2121. }
  2122. interface TestStderr {
  2123. /**
  2124. * The path of the test file.
  2125. */
  2126. file: string;
  2127. /**
  2128. * The message written to `stderr`.
  2129. */
  2130. message: string;
  2131. }
  2132. interface TestStdout {
  2133. /**
  2134. * The path of the test file.
  2135. */
  2136. file: string;
  2137. /**
  2138. * The message written to `stdout`.
  2139. */
  2140. message: string;
  2141. }
  2142. interface TestSummary {
  2143. /**
  2144. * An object containing the counts of various test results.
  2145. */
  2146. counts: {
  2147. /**
  2148. * The total number of cancelled tests.
  2149. */
  2150. cancelled: number;
  2151. /**
  2152. * The total number of passed tests.
  2153. */
  2154. passed: number;
  2155. /**
  2156. * The total number of skipped tests.
  2157. */
  2158. skipped: number;
  2159. /**
  2160. * The total number of suites run.
  2161. */
  2162. suites: number;
  2163. /**
  2164. * The total number of tests run, excluding suites.
  2165. */
  2166. tests: number;
  2167. /**
  2168. * The total number of TODO tests.
  2169. */
  2170. todo: number;
  2171. /**
  2172. * The total number of top level tests and suites.
  2173. */
  2174. topLevel: number;
  2175. };
  2176. /**
  2177. * The duration of the test run in milliseconds.
  2178. */
  2179. duration_ms: number;
  2180. /**
  2181. * The path of the test file that generated the
  2182. * summary. If the summary corresponds to multiple files, this value is
  2183. * `undefined`.
  2184. */
  2185. file: string | undefined;
  2186. /**
  2187. * Indicates whether or not the test run is considered
  2188. * successful or not. If any error condition occurs, such as a failing test or
  2189. * unmet coverage threshold, this value will be set to `false`.
  2190. */
  2191. success: boolean;
  2192. }
  2193. /**
  2194. * The `node:test/reporters` module exposes the builtin-reporters for `node:test`.
  2195. * To access it:
  2196. *
  2197. * ```js
  2198. * import test from 'node:test/reporters';
  2199. * ```
  2200. *
  2201. * This module is only available under the `node:` scheme. The following will not
  2202. * work:
  2203. *
  2204. * ```js
  2205. * import test from 'node:test/reporters';
  2206. * ```
  2207. * @since v19.9.0
  2208. * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test/reporters.js)
  2209. */
  2210. declare module "node:test/reporters" {
  2211. import { Transform, TransformOptions } from "node:stream";
  2212. type TestEvent =
  2213. | { type: "test:coverage"; data: TestCoverage }
  2214. | { type: "test:complete"; data: TestComplete }
  2215. | { type: "test:dequeue"; data: TestDequeue }
  2216. | { type: "test:diagnostic"; data: DiagnosticData }
  2217. | { type: "test:enqueue"; data: TestEnqueue }
  2218. | { type: "test:fail"; data: TestFail }
  2219. | { type: "test:pass"; data: TestPass }
  2220. | { type: "test:plan"; data: TestPlan }
  2221. | { type: "test:start"; data: TestStart }
  2222. | { type: "test:stderr"; data: TestStderr }
  2223. | { type: "test:stdout"; data: TestStdout }
  2224. | { type: "test:summary"; data: TestSummary }
  2225. | { type: "test:watch:drained"; data: undefined };
  2226. type TestEventGenerator = AsyncGenerator<TestEvent, void>;
  2227. interface ReporterConstructorWrapper<T extends new(...args: any[]) => Transform> {
  2228. new(...args: ConstructorParameters<T>): InstanceType<T>;
  2229. (...args: ConstructorParameters<T>): InstanceType<T>;
  2230. }
  2231. /**
  2232. * The `dot` reporter outputs the test results in a compact format,
  2233. * where each passing test is represented by a `.`,
  2234. * and each failing test is represented by a `X`.
  2235. * @since v20.0.0
  2236. */
  2237. function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>;
  2238. /**
  2239. * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format.
  2240. * @since v20.0.0
  2241. */
  2242. function tap(source: TestEventGenerator): AsyncGenerator<string, void>;
  2243. class SpecReporter extends Transform {
  2244. constructor();
  2245. }
  2246. /**
  2247. * The `spec` reporter outputs the test results in a human-readable format.
  2248. * @since v20.0.0
  2249. */
  2250. const spec: ReporterConstructorWrapper<typeof SpecReporter>;
  2251. /**
  2252. * The `junit` reporter outputs test results in a jUnit XML format.
  2253. * @since v21.0.0
  2254. */
  2255. function junit(source: TestEventGenerator): AsyncGenerator<string, void>;
  2256. class LcovReporter extends Transform {
  2257. constructor(opts?: Omit<TransformOptions, "writableObjectMode">);
  2258. }
  2259. /**
  2260. * The `lcov` reporter outputs test coverage when used with the
  2261. * [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v22.x/api/cli.html#--experimental-test-coverage) flag.
  2262. * @since v22.0.0
  2263. */
  2264. // TODO: change the export to a wrapper function once node@0db38f0 is merged (breaking change)
  2265. // const lcov: ReporterConstructorWrapper<typeof LcovReporter>;
  2266. const lcov: LcovReporter;
  2267. export { dot, junit, lcov, spec, tap, TestEvent };
  2268. }