@openclaw/slack 2026.10.5-beta.1 → 2026.10.5-beta.2

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