@types/node 24.0.8 → 24.0.9

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