@types/node 22.15.33 → 22.15.35

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