c95aa94ca840ad78dadbb71c4b8803c12ed861bcee7173de341d591edf1548d3ccc32d588118055f67287e63a7b386b3e4f30080a3862d68fe4548e23319bc 107 KB

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