bun-types 1.2.6 → 1.2.8-canary.20250327T140605

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.
package/test.d.ts CHANGED
@@ -14,1066 +14,1000 @@
14
14
  * ```
15
15
  */
16
16
  declare module "bun:test" {
17
- /**
18
- * -- Mocks --
19
- */
20
- export type Mock<T extends (...args: any[]) => any> = JestMock.Mock<T>;
21
-
22
- export const mock: {
23
- <T extends (...args: any[]) => any>(Function?: T): Mock<T>;
24
-
25
- /**
26
- * Replace the module `id` with the return value of `factory`.
27
- *
28
- * This is useful for mocking modules.
29
- *
30
- * @param id module ID to mock
31
- * @param factory a function returning an object that will be used as the exports of the mocked module
32
- *
33
- * @example
34
- * ## Example
35
- * ```ts
36
- * import { mock } from "bun:test";
37
- *
38
- * mock.module("fs/promises", () => {
39
- * return {
40
- * readFile: () => Promise.resolve("hello world"),
41
- * };
42
- * });
43
- *
44
- * import { readFile } from "fs/promises";
45
- *
46
- * console.log(await readFile("hello.txt", "utf8")); // hello world
47
- * ```
48
- *
49
- * ## More notes
50
- *
51
- * If the module is already loaded, exports are overwritten with the return
52
- * value of `factory`. If the export didn't exist before, it will not be
53
- * added to existing import statements. This is due to how ESM works.
54
- */
55
- module(id: string, factory: () => any): void | Promise<void>;
56
- /**
57
- * Restore the previous value of mocks.
58
- */
59
- restore(): void;
60
- };
61
-
62
- /**
63
- * Control the system time used by:
64
- * - `Date.now()`
65
- * - `new Date()`
66
- * - `Intl.DateTimeFormat().format()`
67
- *
68
- * In the future, we may add support for more functions, but we haven't done that yet.
69
- *
70
- * @param now The time to set the system time to. If not provided, the system time will be reset.
71
- * @returns `this`
72
- * @since v0.6.13
73
- *
74
- * ## Set Date to a specific time
75
- *
76
- * ```js
77
- * import { setSystemTime } from 'bun:test';
78
- *
79
- * setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
80
- * console.log(new Date().toISOString()); // 2020-01-01T00:00:00.000Z
81
- * ```
82
- * ## Reset Date to the current time
83
- *
84
- * ```js
85
- * import { setSystemTime } from 'bun:test';
86
- *
87
- * setSystemTime();
88
- * ```
89
- */
90
- export function setSystemTime(now?: Date | number): ThisType<void>;
91
-
92
- interface Jest {
93
- restoreAllMocks(): void;
94
- clearAllMocks(): void;
95
- fn<T extends (...args: any[]) => any>(func?: T): Mock<T>;
96
- setSystemTime(now?: number | Date): void;
97
- setTimeout(milliseconds: number): void;
98
- }
99
- export const jest: Jest;
100
- export namespace jest {
101
- /**
102
- * Constructs the type of a mock function, e.g. the return type of `jest.fn()`.
103
- */
104
- type Mock<T extends (...args: any[]) => any = (...args: any[]) => any> =
105
- JestMock.Mock<T>;
106
- /**
107
- * Wraps a class, function or object type with Jest mock type definitions.
108
- */
109
- // type Mocked<T extends object> = JestMock.Mocked<T>;
110
- /**
111
- * Wraps a class type with Jest mock type definitions.
112
- */
113
- // type MockedClass<T extends JestMock.ClassLike> = JestMock.MockedClass<T>;
114
- /**
115
- * Wraps a function type with Jest mock type definitions.
116
- */
117
- // type MockedFunction<T extends (...args: any[]) => any> = JestMock.MockedFunction<T>;
118
- /**
119
- * Wraps an object type with Jest mock type definitions.
120
- */
121
- // type MockedObject<T extends object> = JestMock.MockedObject<T>;
122
- /**
123
- * Constructs the type of a replaced property.
124
- */
125
- type Replaced<T> = JestMock.Replaced<T>;
126
- /**
127
- * Constructs the type of a spied class or function.
128
- */
129
- type Spied<T extends JestMock.ClassLike | ((...args: any[]) => any)> =
130
- JestMock.Spied<T>;
131
- /**
132
- * Constructs the type of a spied class.
133
- */
134
- type SpiedClass<T extends JestMock.ClassLike> = JestMock.SpiedClass<T>;
135
- /**
136
- * Constructs the type of a spied function.
137
- */
138
- type SpiedFunction<T extends (...args: any[]) => any> =
139
- JestMock.SpiedFunction<T>;
140
- /**
141
- * Constructs the type of a spied getter.
142
- */
143
- type SpiedGetter<T> = JestMock.SpiedGetter<T>;
144
- /**
145
- * Constructs the type of a spied setter.
146
- */
147
- type SpiedSetter<T> = JestMock.SpiedSetter<T>;
148
- }
149
-
150
- export function spyOn<T extends object, K extends keyof T>(
151
- obj: T,
152
- methodOrPropertyValue: K,
153
- ): Mock<T[K] extends (...args: any[]) => any ? T[K] : never>;
154
-
155
- /**
156
- * Describes a group of related tests.
157
- *
158
- * @example
159
- * function sum(a, b) {
160
- * return a + b;
161
- * }
162
- * describe("sum()", () => {
163
- * test("can sum two values", () => {
164
- * expect(sum(1, 1)).toBe(2);
165
- * });
166
- * });
167
- *
168
- * @param label the label for the tests
169
- * @param fn the function that defines the tests
170
- */
171
-
172
- interface FunctionLike {
173
- readonly name: string;
174
- }
175
- export interface Describe {
176
- (fn: () => void): void;
177
-
178
- (label: number | string | Function | FunctionLike, fn: () => void): void;
179
- /**
180
- * Skips all other tests, except this group of tests.
181
- *
182
- * @param label the label for the tests
183
- * @param fn the function that defines the tests
184
- */
185
- only(label: string, fn: () => void): void;
186
- /**
187
- * Skips this group of tests.
188
- *
189
- * @param label the label for the tests
190
- * @param fn the function that defines the tests
191
- */
192
- skip(label: string, fn: () => void): void;
193
- /**
194
- * Marks this group of tests as to be written or to be fixed.
195
- *
196
- * @param label the label for the tests
197
- * @param fn the function that defines the tests
198
- */
199
- todo(label: string, fn?: () => void): void;
200
- /**
201
- * Runs this group of tests, only if `condition` is true.
202
- *
203
- * This is the opposite of `describe.skipIf()`.
204
- *
205
- * @param condition if these tests should run
206
- */
207
- if(condition: boolean): (label: string, fn: () => void) => void;
208
- /**
209
- * Skips this group of tests, if `condition` is true.
210
- *
211
- * @param condition if these tests should be skipped
212
- */
213
- skipIf(condition: boolean): (label: string, fn: () => void) => void;
214
- /**
215
- * Marks this group of tests as to be written or to be fixed, if `condition` is true.
216
- *
217
- * @param condition if these tests should be skipped
218
- */
219
- todoIf(condition: boolean): (label: string, fn: () => void) => void;
220
- /**
221
- * Returns a function that runs for each item in `table`.
222
- *
223
- * @param table Array of Arrays with the arguments that are passed into the test fn for each row.
224
- */
225
- each<T extends Readonly<[any, ...any[]]>>(
226
- table: readonly T[],
227
- ): (
228
- label: string,
229
- fn: (...args: [...T]) => void | Promise<unknown>,
230
- options?: number | TestOptions,
231
- ) => void;
232
- each<T extends any[]>(
233
- table: readonly T[],
234
- ): (
235
- label: string,
236
- fn: (...args: Readonly<T>) => void | Promise<unknown>,
237
- options?: number | TestOptions,
238
- ) => void;
239
- each<T>(
240
- table: T[],
241
- ): (
242
- label: string,
243
- fn: (...args: T[]) => void | Promise<unknown>,
244
- options?: number | TestOptions,
245
- ) => void;
246
- }
247
- /**
248
- * Describes a group of related tests.
249
- *
250
- * @example
251
- * function sum(a, b) {
252
- * return a + b;
253
- * }
254
- * describe("sum()", () => {
255
- * test("can sum two values", () => {
256
- * expect(sum(1, 1)).toBe(2);
257
- * });
258
- * });
259
- *
260
- * @param label the label for the tests
261
- * @param fn the function that defines the tests
262
- */
263
- export const describe: Describe;
264
- /**
265
- * Runs a function, once, before all the tests.
266
- *
267
- * This is useful for running set up tasks, like initializing
268
- * a global variable or connecting to a database.
269
- *
270
- * If this function throws, tests will not run in this file.
271
- *
272
- * @example
273
- * let database;
274
- * beforeAll(async () => {
275
- * database = await connect("localhost");
276
- * });
277
- *
278
- * @param fn the function to run
279
- */
280
- export function beforeAll(
281
- fn:
282
- | (() => void | Promise<unknown>)
283
- | ((done: (err?: unknown) => void) => void),
284
- ): void;
285
- /**
286
- * Runs a function before each test.
287
- *
288
- * This is useful for running set up tasks, like initializing
289
- * a global variable or connecting to a database.
290
- *
291
- * If this function throws, the test will not run.
292
- *
293
- * @param fn the function to run
294
- */
295
- export function beforeEach(
296
- fn:
297
- | (() => void | Promise<unknown>)
298
- | ((done: (err?: unknown) => void) => void),
299
- ): void;
300
- /**
301
- * Runs a function, once, after all the tests.
302
- *
303
- * This is useful for running clean up tasks, like closing
304
- * a socket or deleting temporary files.
305
- *
306
- * @example
307
- * let database;
308
- * afterAll(async () => {
309
- * if (database) {
310
- * await database.close();
311
- * }
312
- * });
313
- *
314
- * @param fn the function to run
315
- */
316
- export function afterAll(
317
- fn:
318
- | (() => void | Promise<unknown>)
319
- | ((done: (err?: unknown) => void) => void),
320
- ): void;
321
- /**
322
- * Runs a function after each test.
323
- *
324
- * This is useful for running clean up tasks, like closing
325
- * a socket or deleting temporary files.
326
- *
327
- * @param fn the function to run
328
- */
329
- export function afterEach(
330
- fn:
331
- | (() => void | Promise<unknown>)
332
- | ((done: (err?: unknown) => void) => void),
333
- ): void;
334
- /**
335
- * Sets the default timeout for all tests in the current file. If a test specifies a timeout, it will
336
- * override this value. The default timeout is 5000ms (5 seconds).
337
- *
338
- * @param milliseconds the number of milliseconds for the default timeout
339
- */
340
- export function setDefaultTimeout(milliseconds: number): void;
341
- export interface TestOptions {
342
- /**
343
- * Sets the timeout for the test in milliseconds.
344
- *
345
- * If the test does not complete within this time, the test will fail with:
346
- * ```ts
347
- * 'Timeout: test {name} timed out after 5000ms'
348
- * ```
349
- *
350
- * @default 5000 // 5 seconds
351
- */
352
- timeout?: number;
353
- /**
354
- * Sets the number of times to retry the test if it fails.
355
- *
356
- * @default 0
357
- */
358
- retry?: number;
359
- /**
360
- * Sets the number of times to repeat the test, regardless of whether it passed or failed.
361
- *
362
- * @default 0
363
- */
364
- repeats?: number;
365
- }
366
- /**
367
- * Runs a test.
368
- *
369
- * @example
370
- * test("can check if using Bun", () => {
371
- * expect(Bun).toBeDefined();
372
- * });
373
- *
374
- * test("can make a fetch() request", async () => {
375
- * const response = await fetch("https://example.com/");
376
- * expect(response.ok).toBe(true);
377
- * });
378
- *
379
- * test("can set a timeout", async () => {
380
- * await Bun.sleep(100);
381
- * }, 50); // or { timeout: 50 }
382
- *
383
- * @param label the label for the test
384
- * @param fn the test function
385
- * @param options the test timeout or options
386
- */
387
- export interface Test {
388
- (
389
- label: string,
390
- fn:
391
- | (() => void | Promise<unknown>)
392
- | ((done: (err?: unknown) => void) => void),
393
- /**
394
- * - If a `number`, sets the timeout for the test in milliseconds.
395
- * - If an `object`, sets the options for the test.
396
- * - `timeout` sets the timeout for the test in milliseconds.
397
- * - `retry` sets the number of times to retry the test if it fails.
398
- * - `repeats` sets the number of times to repeat the test, regardless of whether it passed or failed.
399
- */
400
- options?: number | TestOptions,
401
- ): void;
402
- /**
403
- * Skips all other tests, except this test when run with the `--only` option.
404
- *
405
- * @param label the label for the test
406
- * @param fn the test function
407
- * @param options the test timeout or options
408
- */
409
- only(
410
- label: string,
411
- fn:
412
- | (() => void | Promise<unknown>)
413
- | ((done: (err?: unknown) => void) => void),
414
- options?: number | TestOptions,
415
- ): void;
416
- /**
417
- * Skips this test.
418
- *
419
- * @param label the label for the test
420
- * @param fn the test function
421
- * @param options the test timeout or options
422
- */
423
- skip(
424
- label: string,
425
- fn:
426
- | (() => void | Promise<unknown>)
427
- | ((done: (err?: unknown) => void) => void),
428
- options?: number | TestOptions,
429
- ): void;
430
- /**
431
- * Marks this test as to be written or to be fixed.
432
- *
433
- * These tests will not be executed unless the `--todo` flag is passed. With the flag,
434
- * if the test passes, the test will be marked as `fail` in the results; you will have to
435
- * remove the `.todo` or check that your test
436
- * is implemented correctly.
437
- *
438
- * @param label the label for the test
439
- * @param fn the test function
440
- * @param options the test timeout or options
441
- */
442
- todo(
443
- label: string,
444
- fn?:
445
- | (() => void | Promise<unknown>)
446
- | ((done: (err?: unknown) => void) => void),
447
- options?: number | TestOptions,
448
- ): void;
449
- /**
450
- * Marks this test as failing.
451
- *
452
- * Use `test.failing` when you are writing a test and expecting it to fail.
453
- * These tests will behave the other way normal tests do. If failing test
454
- * will throw any errors then it will pass. If it does not throw it will
455
- * fail.
456
- *
457
- * `test.failing` is very similar to {@link test.todo} except that it always
458
- * runs, regardless of the `--todo` flag.
459
- *
460
- * @param label the label for the test
461
- * @param fn the test function
462
- * @param options the test timeout or options
463
- */
464
- failing(
465
- label: string,
466
- fn?:
467
- | (() => void | Promise<unknown>)
468
- | ((done: (err?: unknown) => void) => void),
469
- ): void;
470
- /**
471
- * Runs this test, if `condition` is true.
472
- *
473
- * This is the opposite of `test.skipIf()`.
474
- *
475
- * @param condition if the test should run
476
- */
477
- if(
478
- condition: boolean,
479
- ): (
480
- label: string,
481
- fn:
482
- | (() => void | Promise<unknown>)
483
- | ((done: (err?: unknown) => void) => void),
484
- options?: number | TestOptions,
485
- ) => void;
486
- /**
487
- * Skips this test, if `condition` is true.
488
- *
489
- * @param condition if the test should be skipped
490
- */
491
- skipIf(
492
- condition: boolean,
493
- ): (
494
- label: string,
495
- fn:
496
- | (() => void | Promise<unknown>)
497
- | ((done: (err?: unknown) => void) => void),
498
- options?: number | TestOptions,
499
- ) => void;
500
- /**
501
- * Marks this test as to be written or to be fixed, if `condition` is true.
502
- *
503
- * @param condition if the test should be marked TODO
504
- */
505
- todoIf(
506
- condition: boolean,
507
- ): (
508
- label: string,
509
- fn:
510
- | (() => void | Promise<unknown>)
511
- | ((done: (err?: unknown) => void) => void),
512
- options?: number | TestOptions,
513
- ) => void;
514
- /**
515
- * Returns a function that runs for each item in `table`.
516
- *
517
- * @param table Array of Arrays with the arguments that are passed into the test fn for each row.
518
- */
519
- each<T extends Readonly<[any, ...any[]]>>(
520
- table: readonly T[],
521
- ): (
522
- label: string,
523
- fn: (...args: [...T]) => void | Promise<unknown>,
524
- options?: number | TestOptions,
525
- ) => void;
526
- each<T extends any[]>(
527
- table: readonly T[],
528
- ): (
529
- label: string,
530
- fn: (...args: Readonly<T>) => void | Promise<unknown>,
531
- options?: number | TestOptions,
532
- ) => void;
533
- each<T>(
534
- table: T[],
535
- ): (
536
- label: string,
537
- fn: (...args: T[]) => void | Promise<unknown>,
538
- options?: number | TestOptions,
539
- ) => void;
540
- }
541
- /**
542
- * Runs a test.
543
- *
544
- * @example
545
- * test("can check if using Bun", () => {
546
- * expect(Bun).toBeDefined();
547
- * });
548
- *
549
- * test("can make a fetch() request", async () => {
550
- * const response = await fetch("https://example.com/");
551
- * expect(response.ok).toBe(true);
552
- * });
553
- *
554
- * @param label the label for the test
555
- * @param fn the test function
556
- */
557
- export const test: Test;
558
- export { test as it };
559
-
560
- /**
561
- * Asserts that a value matches some criteria.
562
- *
563
- * @link https://jestjs.io/docs/expect#reference
564
- * @example
565
- * expect(1 + 1).toBe(2);
566
- * expect([1,2,3]).toContain(2);
567
- * expect(null).toBeNull();
568
- *
569
- * @param actual The actual (received) value
570
- */
571
- export const expect: Expect;
572
-
573
- type ExpectNot = Omit<AsymmetricMatchers, keyof AsymmetricMatchersBuiltin> &
574
- AsymmetricMatchersBuiltinNegated;
575
-
576
- export interface Expect extends AsymmetricMatchers {
577
- // the `expect()` callable signature
578
- /**
579
- * @param actual the actual value
580
- * @param customFailMessage an optional custom message to display if the test fails.
581
- * */
582
-
583
- <T = unknown>(actual?: T, customFailMessage?: string): Matchers<T>;
584
-
585
- /**
586
- * Access to negated asymmetric matchers.
587
- *
588
- * @example
589
- * expect("abc").toEqual(expect.stringContaining("abc")); // will pass
590
- * expect("abc").toEqual(expect.not.stringContaining("abc")); // will fail
591
- */
592
- not: ExpectNot;
593
-
594
- /**
595
- * Create an asymmetric matcher for a promise resolved value.
596
- *
597
- * @example
598
- * expect(Promise.resolve("value")).toEqual(expect.resolvesTo.stringContaining("value")); // will pass
599
- * expect(Promise.reject("value")).toEqual(expect.resolvesTo.stringContaining("value")); // will fail
600
- * expect("value").toEqual(expect.resolvesTo.stringContaining("value")); // will fail
601
- */
602
- resolvesTo: AsymmetricMatchers;
603
-
604
- /**
605
- * Create an asymmetric matcher for a promise rejected value.
606
- *
607
- * @example
608
- * expect(Promise.reject("error")).toEqual(expect.rejectsTo.stringContaining("error")); // will pass
609
- * expect(Promise.resolve("error")).toEqual(expect.rejectsTo.stringContaining("error")); // will fail
610
- * expect("error").toEqual(expect.rejectsTo.stringContaining("error")); // will fail
611
- */
612
- rejectsTo: AsymmetricMatchers;
613
-
614
- /**
615
- * Register new custom matchers.
616
- * @param matchers An object containing the matchers to register, where each key is the matcher name, and its value the implementation function.
617
- * The function must satisfy: `(actualValue, ...matcherInstantiationArguments) => { pass: true|false, message: () => string }`
618
- *
619
- * @example
620
- * expect.extend({
621
- * toBeWithinRange(actual, min, max) {
622
- * if (typeof actual !== 'number' || typeof min !== 'number' || typeof max !== 'number')
623
- * throw new Error('Invalid usage');
624
- * const pass = actual >= min && actual <= max;
625
- * return {
626
- * pass: pass,
627
- * message: () => `expected ${this.utils.printReceived(actual)} ` +
628
- * (pass ? `not to be`: `to be`) + ` within range ${this.utils.printExpected(`${min} .. ${max}`)}`,
629
- * };
630
- * },
631
- * });
632
- *
633
- * test('some test', () => {
634
- * expect(50).toBeWithinRange(0, 100); // will pass
635
- * expect(50).toBeWithinRange(100, 200); // will fail
636
- * expect(50).toBe(expect.toBeWithinRange(0, 100)); // will pass
637
- * expect(50).toBe(expect.not.toBeWithinRange(100, 200)); // will pass
638
- * });
639
- */
640
- extend<M>(matchers: ExpectExtendMatchers<M>): void;
641
-
642
- /**
643
- * Throw an error if this function is called.
644
- *
645
- * @param msg Optional message to display if the test fails
646
- * @returns never
647
- *
648
- * @example
649
- * ## Example
650
- *
651
- * ```ts
652
- * import { expect, test } from "bun:test";
653
- *
654
- * test("!!abc!! is not a module", () => {
655
- * try {
656
- * require("!!abc!!");
657
- * expect.unreachable();
658
- * } catch(e) {
659
- * expect(e.name).not.toBe("UnreachableError");
660
- * }
661
- * });
662
- * ```
663
- */
664
- unreachable(msg?: string | Error): never;
665
-
666
- /**
667
- * Ensures that an assertion is made
668
- */
669
- hasAssertions(): void;
670
-
671
- /**
672
- * Ensures that a specific number of assertions are made
673
- */
674
- assertions(neededAssertions: number): void;
675
- }
676
-
677
- /**
678
- * You can extend this interface with declaration merging, in order to add type support for custom matchers.
679
- * @template T Type of the actual value
680
- *
681
- * @example
682
- * // my_modules.d.ts
683
- * interface MyCustomMatchers {
684
- * toBeWithinRange(floor: number, ceiling: number): any;
685
- * }
686
- * declare module "bun:test" {
687
- * interface Matchers<T> extends MyCustomMatchers {}
688
- * interface AsymmetricMatchers extends MyCustomMatchers {}
689
- * }
690
- *
691
- * @example
692
- * // my_modules.d.ts (alternatively)
693
- * declare module "bun:test" {
694
- * interface Matchers<T> {
695
- * toBeWithinRange(floor: number, ceiling: number): any;
696
- * }
697
- * interface AsymmetricMatchers {
698
- * toBeWithinRange(floor: number, ceiling: number): any;
699
- * }
700
- * }
701
- */
702
- export interface Matchers<T = unknown> extends MatchersBuiltin<T> {}
703
-
704
- /**
705
- * You can extend this interface with declaration merging, in order to add type support for custom asymmetric matchers.
706
- * @example
707
- * // my_modules.d.ts
708
- * interface MyCustomMatchers {
709
- * toBeWithinRange(floor: number, ceiling: number): any;
710
- * }
711
- * declare module "bun:test" {
712
- * interface Matchers<T> extends MyCustomMatchers {}
713
- * interface AsymmetricMatchers extends MyCustomMatchers {}
714
- * }
715
- *
716
- * @example
717
- * // my_modules.d.ts (alternatively)
718
- * declare module "bun:test" {
719
- * interface Matchers<T> {
720
- * toBeWithinRange(floor: number, ceiling: number): any;
721
- * }
722
- * interface AsymmetricMatchers {
723
- * toBeWithinRange(floor: number, ceiling: number): any;
724
- * }
725
- * }
726
- */
727
- export interface AsymmetricMatchers extends AsymmetricMatchersBuiltin {}
728
-
729
- export interface AsymmetricMatchersBuiltin {
730
- /**
731
- * Matches anything that was created with the given constructor.
732
- * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
733
- *
734
- * @example
735
- *
736
- * function randocall(fn) {
737
- * return fn(Math.floor(Math.random() * 6 + 1));
738
- * }
739
- *
740
- * test('randocall calls its callback with a number', () => {
741
- * const mock = jest.fn();
742
- * randocall(mock);
743
- * expect(mock).toBeCalledWith(expect.any(Number));
744
- * });
745
- */
746
- any(
747
- constructor: ((...args: any[]) => any) | { new (...args: any[]): any },
748
- ): AsymmetricMatcher;
749
- /**
750
- * Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead
751
- * of a literal value. For example, if you want to check that a mock function is called with a
752
- * non-null argument:
753
- *
754
- * @example
755
- *
756
- * test('map calls its argument with a non-null argument', () => {
757
- * const mock = jest.fn();
758
- * [1].map(x => mock(x));
759
- * expect(mock).toBeCalledWith(expect.anything());
760
- * });
761
- */
762
- anything(): AsymmetricMatcher;
763
- /**
764
- * Matches any array made up entirely of elements in the provided array.
765
- * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
766
- *
767
- * Optionally, you can provide a type for the elements via a generic.
768
- */
769
- arrayContaining<E = any>(arr: readonly E[]): AsymmetricMatcher;
770
- /**
771
- * Matches any object that recursively matches the provided keys.
772
- * This is often handy in conjunction with other asymmetric matchers.
773
- *
774
- * Optionally, you can provide a type for the object via a generic.
775
- * This ensures that the object contains the desired structure.
776
- */
777
- objectContaining(obj: object): AsymmetricMatcher;
778
- /**
779
- * Matches any received string that contains the exact expected string
780
- */
781
- stringContaining(str: string | String): AsymmetricMatcher;
782
- /**
783
- * Matches any string that contains the exact provided string
784
- */
785
- stringMatching(regex: string | String | RegExp): AsymmetricMatcher;
786
- /**
787
- * Useful when comparing floating point numbers in object properties or array item.
788
- * If you need to compare a number, use `.toBeCloseTo` instead.
789
- *
790
- * The optional `numDigits` argument limits the number of digits to check after the decimal point.
791
- * For the default value 2, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`).
792
- */
793
- closeTo(num: number, numDigits?: number): AsymmetricMatcher;
794
- }
795
-
796
- interface AsymmetricMatchersBuiltinNegated {
797
- /**
798
- * Create an asymmetric matcher that will fail on a promise resolved value that matches the chained matcher.
799
- *
800
- * @example
801
- * expect(Promise.resolve("value")).toEqual(expect.not.resolvesTo.stringContaining("value")); // will fail
802
- * expect(Promise.reject("value")).toEqual(expect.not.resolvesTo.stringContaining("value")); // will pass
803
- * expect("value").toEqual(expect.not.resolvesTo.stringContaining("value")); // will pass
804
- */
805
- resolvesTo: ExpectNot;
806
-
807
- /**
808
- * Create an asymmetric matcher that will fail on a promise rejected value that matches the chained matcher.
809
- *
810
- * @example
811
- * expect(Promise.reject("value")).toEqual(expect.not.rejectsTo.stringContaining("value")); // will fail
812
- * expect(Promise.resolve("value")).toEqual(expect.not.rejectsTo.stringContaining("value")); // will pass
813
- * expect("value").toEqual(expect.not.rejectsTo.stringContaining("value")); // will pass
814
- */
815
- rejectsTo: ExpectNot;
816
-
817
- /**
818
- * `expect.not.arrayContaining(array)` matches a received array which
819
- * does not contain all of the elements in the expected array. That is,
820
- * the expected array is not a subset of the received array. It is the
821
- * inverse of `expect.arrayContaining`.
822
- *
823
- * Optionally, you can provide a type for the elements via a generic.
824
- */
825
- arrayContaining<E = any>(arr: readonly E[]): AsymmetricMatcher;
826
-
827
- /**
828
- * `expect.not.objectContaining(object)` matches any received object
829
- * that does not recursively match the expected properties. That is, the
830
- * expected object is not a subset of the received object. Therefore,
831
- * it matches a received object which contains properties that are not
832
- * in the expected object. It is the inverse of `expect.objectContaining`.
833
- *
834
- * Optionally, you can provide a type for the object via a generic.
835
- * This ensures that the object contains the desired structure.
836
- */
837
- objectContaining(obj: object): AsymmetricMatcher;
838
-
839
- /**
840
- * `expect.not.stringContaining(string)` matches the received string
841
- * that does not contain the exact expected string. It is the inverse of
842
- * `expect.stringContaining`.
843
- */
844
- stringContaining(str: string | String): AsymmetricMatcher;
845
-
846
- /**
847
- * `expect.not.stringMatching(string | regexp)` matches the received
848
- * string that does not match the expected regexp. It is the inverse of
849
- * `expect.stringMatching`.
850
- */
851
- stringMatching(str: string | String | RegExp): AsymmetricMatcher;
852
-
853
- /**
854
- * `expect.not.closeTo` matches a number not close to the provided value.
855
- * Useful when comparing floating point numbers in object properties or array item.
856
- * It is the inverse of `expect.closeTo`.
857
- */
858
- closeTo(num: number, numDigits?: number): AsymmetricMatcher;
859
- }
860
-
861
- export interface MatchersBuiltin<T = unknown> {
862
- /**
863
- * Negates the result of a subsequent assertion.
864
- * If you know how to test something, `.not` lets you test its opposite.
865
- *
866
- * @example
867
- * expect(1).not.toBe(0);
868
- * expect(null).not.toBeNull();
869
- *
870
- * @example
871
- * expect(42).toEqual(42); // will pass
872
- * expect(42).not.toEqual(42); // will fail
873
- */
874
- not: Matchers<unknown>;
875
-
876
- /**
877
- * Expects the value to be a promise that resolves.
878
- *
879
- * @example
880
- * expect(Promise.resolve(1)).resolves.toBe(1);
881
- */
882
- resolves: Matchers<Awaited<T>>;
883
-
884
- /**
885
- * Expects the value to be a promise that rejects.
886
- *
887
- * @example
888
- * expect(Promise.reject("error")).rejects.toBe("error");
889
- */
890
- rejects: Matchers<unknown>;
891
-
892
- /**
893
- * Assertion which passes.
894
- *
895
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/pass
896
- * @example
897
- * expect().pass();
898
- * expect().pass("message is optional");
899
- * expect().not.pass();
900
- * expect().not.pass("hi");
901
- *
902
- * @param message the message to display if the test fails (optional)
903
- */
904
- pass: (message?: string) => void;
905
- /**
906
- * Assertion which fails.
907
- *
908
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/fail
909
- * @example
910
- * expect().fail();
911
- * expect().fail("message is optional");
912
- * expect().not.fail();
913
- * expect().not.fail("hi");
914
- */
915
- fail: (message?: string) => void;
916
- /**
917
- * Asserts that a value equals what is expected.
918
- *
919
- * - For non-primitive values, like objects and arrays,
920
- * use `toEqual()` instead.
921
- * - For floating-point numbers, use `toBeCloseTo()` instead.
922
- *
923
- * @example
924
- * expect(100 + 23).toBe(123);
925
- * expect("d" + "og").toBe("dog");
926
- * expect([123]).toBe([123]); // fail, use toEqual()
927
- * expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo()
928
- *
929
- * @param expected the expected value
930
- */
931
- toBe(expected: T): void;
932
- /**
933
- * Asserts that a number is odd.
934
- *
935
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/number/#tobeodd
936
- * @example
937
- * expect(1).toBeOdd();
938
- * expect(2).not.toBeOdd();
939
- */
940
- toBeOdd(): void;
941
- /**
942
- * Asserts that a number is even.
943
- *
944
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/number/#tobeeven
945
- * @example
946
- * expect(2).toBeEven();
947
- * expect(1).not.toBeEven();
948
- */
949
- toBeEven(): void;
950
- /**
951
- * Asserts that value is close to the expected by floating point precision.
952
- *
953
- * For example, the following fails because arithmetic on decimal (base 10)
954
- * values often have rounding errors in limited precision binary (base 2) representation.
955
- *
956
- * @example
957
- * expect(0.2 + 0.1).toBe(0.3); // fails
958
- *
959
- * Use `toBeCloseTo` to compare floating point numbers for approximate equality.
960
- *
961
- * @example
962
- * expect(0.2 + 0.1).toBeCloseTo(0.3, 5); // passes
963
- *
964
- * @param expected the expected value
965
- * @param numDigits the number of digits to check after the decimal point. Default is `2`
966
- */
967
- toBeCloseTo(expected: number, numDigits?: number): void;
968
- /**
969
- * Asserts that a value is deeply equal to what is expected.
970
- *
971
- * @example
972
- * expect(100 + 23).toBe(123);
973
- * expect("d" + "og").toBe("dog");
974
- * expect([456]).toEqual([456]);
975
- * expect({ value: 1 }).toEqual({ value: 1 });
976
- *
977
- * @param expected the expected value
978
- */
979
- toEqual(expected: T): void;
980
- /**
981
- * Asserts that a value is deeply and strictly equal to
982
- * what is expected.
983
- *
984
- * There are two key differences from `toEqual()`:
985
- * 1. It checks that the class is the same.
986
- * 2. It checks that `undefined` values match as well.
987
- *
988
- * @example
989
- * class Dog {
990
- * type = "dog";
991
- * }
992
- * const actual = new Dog();
993
- * expect(actual).toStrictEqual(new Dog());
994
- * expect(actual).toStrictEqual({ type: "dog" }); // fail
995
- *
996
- * @example
997
- * const actual = { value: 1, name: undefined };
998
- * expect(actual).toEqual({ value: 1 });
999
- * expect(actual).toStrictEqual({ value: 1 }); // fail
1000
- *
1001
- * @param expected the expected value
1002
- */
1003
- toStrictEqual(expected: T): void;
1004
- /**
1005
- * Asserts that the value is deep equal to an element in the expected array.
1006
- *
1007
- * The value must be an array or iterable, which includes strings.
1008
- *
1009
- * @example
1010
- * expect(1).toBeOneOf([1,2,3]);
1011
- * expect("foo").toBeOneOf(["foo", "bar"]);
1012
- * expect(true).toBeOneOf(new Set([true]));
1013
- *
1014
- * @param expected the expected value
1015
- */
1016
- toBeOneOf(expected: Array<unknown> | Iterable<unknown>): void;
1017
- /**
1018
- * Asserts that a value contains what is expected.
1019
- *
1020
- * The value must be an array or iterable, which
1021
- * includes strings.
1022
- *
1023
- * @example
1024
- * expect([1, 2, 3]).toContain(1);
1025
- * expect(new Set([true])).toContain(true);
1026
- * expect("hello").toContain("o");
1027
- *
1028
- * @param expected the expected value
1029
- */
1030
- toContain(expected: unknown): void;
1031
- /**
1032
- * Asserts that an `object` contains a key.
1033
- *
1034
- * The value must be an object
1035
- *
1036
- * @example
1037
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKey('a');
1038
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKey('b');
1039
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKey('c');
1040
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).not.toContainKey('d');
1041
- *
1042
- * @param expected the expected value
1043
- */
1044
- toContainKey(expected: unknown): void;
1045
- /**
1046
- * Asserts that an `object` contains all the provided keys.
1047
- *
1048
- * The value must be an object
1049
- *
1050
- * @example
1051
- * expect({ a: 'hello', b: 'world' }).toContainAllKeys(['a','b']);
1052
- * expect({ a: 'hello', b: 'world' }).toContainAllKeys(['b','a']);
1053
- * expect({ 1: 'hello', b: 'world' }).toContainAllKeys([1,'b']);
1054
- * expect({ a: 'hello', b: 'world' }).not.toContainAllKeys(['c']);
1055
- * expect({ a: 'hello', b: 'world' }).not.toContainAllKeys(['a']);
1056
- *
1057
- * @param expected the expected value
1058
- */
1059
- toContainAllKeys(expected: unknown): void;
1060
- /**
1061
- * Asserts that an `object` contains at least one of the provided keys.
1062
- * Asserts that an `object` contains all the provided keys.
1063
- *
1064
- * The value must be an object
1065
- *
1066
- * @example
1067
- * expect({ a: 'hello', b: 'world' }).toContainAnyKeys(['a']);
1068
- * expect({ a: 'hello', b: 'world' }).toContainAnyKeys(['b']);
1069
- * expect({ a: 'hello', b: 'world' }).toContainAnyKeys(['b', 'c']);
1070
- * expect({ a: 'hello', b: 'world' }).not.toContainAnyKeys(['c']);
1071
- *
1072
- * @param expected the expected value
1073
- */
1074
- toContainAnyKeys(expected: unknown): void;
1075
-
1076
- /**
17
+ /**
18
+ * -- Mocks --
19
+ */
20
+ export type Mock<T extends (...args: any[]) => any> = JestMock.Mock<T>;
21
+
22
+ export const mock: {
23
+ <T extends (...args: any[]) => any>(Function?: T): Mock<T>;
24
+
25
+ /**
26
+ * Replace the module `id` with the return value of `factory`.
27
+ *
28
+ * This is useful for mocking modules.
29
+ *
30
+ * @param id module ID to mock
31
+ * @param factory a function returning an object that will be used as the exports of the mocked module
32
+ *
33
+ * @example
34
+ * ## Example
35
+ * ```ts
36
+ * import { mock } from "bun:test";
37
+ *
38
+ * mock.module("fs/promises", () => {
39
+ * return {
40
+ * readFile: () => Promise.resolve("hello world"),
41
+ * };
42
+ * });
43
+ *
44
+ * import { readFile } from "fs/promises";
45
+ *
46
+ * console.log(await readFile("hello.txt", "utf8")); // hello world
47
+ * ```
48
+ *
49
+ * ## More notes
50
+ *
51
+ * If the module is already loaded, exports are overwritten with the return
52
+ * value of `factory`. If the export didn't exist before, it will not be
53
+ * added to existing import statements. This is due to how ESM works.
54
+ */
55
+ module(id: string, factory: () => any): void | Promise<void>;
56
+ /**
57
+ * Restore the previous value of mocks.
58
+ */
59
+ restore(): void;
60
+ };
61
+
62
+ /**
63
+ * Control the system time used by:
64
+ * - `Date.now()`
65
+ * - `new Date()`
66
+ * - `Intl.DateTimeFormat().format()`
67
+ *
68
+ * In the future, we may add support for more functions, but we haven't done that yet.
69
+ *
70
+ * @param now The time to set the system time to. If not provided, the system time will be reset.
71
+ * @returns `this`
72
+ * @since v0.6.13
73
+ *
74
+ * ## Set Date to a specific time
75
+ *
76
+ * ```js
77
+ * import { setSystemTime } from 'bun:test';
78
+ *
79
+ * setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
80
+ * console.log(new Date().toISOString()); // 2020-01-01T00:00:00.000Z
81
+ * ```
82
+ * ## Reset Date to the current time
83
+ *
84
+ * ```js
85
+ * import { setSystemTime } from 'bun:test';
86
+ *
87
+ * setSystemTime();
88
+ * ```
89
+ */
90
+ export function setSystemTime(now?: Date | number): ThisType<void>;
91
+
92
+ interface Jest {
93
+ restoreAllMocks(): void;
94
+ clearAllMocks(): void;
95
+ fn<T extends (...args: any[]) => any>(func?: T): Mock<T>;
96
+ setSystemTime(now?: number | Date): void;
97
+ setTimeout(milliseconds: number): void;
98
+ }
99
+ export const jest: Jest;
100
+ export namespace jest {
101
+ /**
102
+ * Constructs the type of a mock function, e.g. the return type of `jest.fn()`.
103
+ */
104
+ type Mock<T extends (...args: any[]) => any = (...args: any[]) => any> = JestMock.Mock<T>;
105
+ /**
106
+ * Wraps a class, function or object type with Jest mock type definitions.
107
+ */
108
+ // type Mocked<T extends object> = JestMock.Mocked<T>;
109
+ /**
110
+ * Wraps a class type with Jest mock type definitions.
111
+ */
112
+ // type MockedClass<T extends JestMock.ClassLike> = JestMock.MockedClass<T>;
113
+ /**
114
+ * Wraps a function type with Jest mock type definitions.
115
+ */
116
+ // type MockedFunction<T extends (...args: any[]) => any> = JestMock.MockedFunction<T>;
117
+ /**
118
+ * Wraps an object type with Jest mock type definitions.
119
+ */
120
+ // type MockedObject<T extends object> = JestMock.MockedObject<T>;
121
+ /**
122
+ * Constructs the type of a replaced property.
123
+ */
124
+ type Replaced<T> = JestMock.Replaced<T>;
125
+ /**
126
+ * Constructs the type of a spied class or function.
127
+ */
128
+ type Spied<T extends JestMock.ClassLike | ((...args: any[]) => any)> = JestMock.Spied<T>;
129
+ /**
130
+ * Constructs the type of a spied class.
131
+ */
132
+ type SpiedClass<T extends JestMock.ClassLike> = JestMock.SpiedClass<T>;
133
+ /**
134
+ * Constructs the type of a spied function.
135
+ */
136
+ type SpiedFunction<T extends (...args: any[]) => any> = JestMock.SpiedFunction<T>;
137
+ /**
138
+ * Constructs the type of a spied getter.
139
+ */
140
+ type SpiedGetter<T> = JestMock.SpiedGetter<T>;
141
+ /**
142
+ * Constructs the type of a spied setter.
143
+ */
144
+ type SpiedSetter<T> = JestMock.SpiedSetter<T>;
145
+ }
146
+
147
+ export function spyOn<T extends object, K extends keyof T>(
148
+ obj: T,
149
+ methodOrPropertyValue: K,
150
+ ): Mock<T[K] extends (...args: any[]) => any ? T[K] : never>;
151
+
152
+ interface FunctionLike {
153
+ readonly name: string;
154
+ }
155
+
156
+ /**
157
+ * Describes a group of related tests.
158
+ *
159
+ * @example
160
+ * function sum(a, b) {
161
+ * return a + b;
162
+ * }
163
+ * describe("sum()", () => {
164
+ * test("can sum two values", () => {
165
+ * expect(sum(1, 1)).toBe(2);
166
+ * });
167
+ * });
168
+ *
169
+ * @param label the label for the tests
170
+ * @param fn the function that defines the tests
171
+ */
172
+ export interface Describe {
173
+ (fn: () => void): void;
174
+
175
+ (label: number | string | Function | FunctionLike, fn: () => void): void;
176
+ /**
177
+ * Skips all other tests, except this group of tests.
178
+ *
179
+ * @param label the label for the tests
180
+ * @param fn the function that defines the tests
181
+ */
182
+ only(label: string, fn: () => void): void;
183
+ /**
184
+ * Skips this group of tests.
185
+ *
186
+ * @param label the label for the tests
187
+ * @param fn the function that defines the tests
188
+ */
189
+ skip(label: string, fn: () => void): void;
190
+ /**
191
+ * Marks this group of tests as to be written or to be fixed.
192
+ *
193
+ * @param label the label for the tests
194
+ * @param fn the function that defines the tests
195
+ */
196
+ todo(label: string, fn?: () => void): void;
197
+ /**
198
+ * Runs this group of tests, only if `condition` is true.
199
+ *
200
+ * This is the opposite of `describe.skipIf()`.
201
+ *
202
+ * @param condition if these tests should run
203
+ */
204
+ if(condition: boolean): (label: string, fn: () => void) => void;
205
+ /**
206
+ * Skips this group of tests, if `condition` is true.
207
+ *
208
+ * @param condition if these tests should be skipped
209
+ */
210
+ skipIf(condition: boolean): (label: string, fn: () => void) => void;
211
+ /**
212
+ * Marks this group of tests as to be written or to be fixed, if `condition` is true.
213
+ *
214
+ * @param condition if these tests should be skipped
215
+ */
216
+ todoIf(condition: boolean): (label: string, fn: () => void) => void;
217
+ /**
218
+ * Returns a function that runs for each item in `table`.
219
+ *
220
+ * @param table Array of Arrays with the arguments that are passed into the test fn for each row.
221
+ */
222
+ each<T extends Readonly<[any, ...any[]]>>(
223
+ table: readonly T[],
224
+ ): (label: string, fn: (...args: [...T]) => void | Promise<unknown>, options?: number | TestOptions) => void;
225
+ each<T extends any[]>(
226
+ table: readonly T[],
227
+ ): (label: string, fn: (...args: Readonly<T>) => void | Promise<unknown>, options?: number | TestOptions) => void;
228
+ each<T>(
229
+ table: T[],
230
+ ): (label: string, fn: (...args: T[]) => void | Promise<unknown>, options?: number | TestOptions) => void;
231
+ }
232
+ /**
233
+ * Describes a group of related tests.
234
+ *
235
+ * @example
236
+ * function sum(a, b) {
237
+ * return a + b;
238
+ * }
239
+ * describe("sum()", () => {
240
+ * test("can sum two values", () => {
241
+ * expect(sum(1, 1)).toBe(2);
242
+ * });
243
+ * });
244
+ *
245
+ * @param label the label for the tests
246
+ * @param fn the function that defines the tests
247
+ */
248
+ export const describe: Describe;
249
+ /**
250
+ * Runs a function, once, before all the tests.
251
+ *
252
+ * This is useful for running set up tasks, like initializing
253
+ * a global variable or connecting to a database.
254
+ *
255
+ * If this function throws, tests will not run in this file.
256
+ *
257
+ * @example
258
+ * let database;
259
+ * beforeAll(async () => {
260
+ * database = await connect("localhost");
261
+ * });
262
+ *
263
+ * @param fn the function to run
264
+ */
265
+ export function beforeAll(fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void)): void;
266
+ /**
267
+ * Runs a function before each test.
268
+ *
269
+ * This is useful for running set up tasks, like initializing
270
+ * a global variable or connecting to a database.
271
+ *
272
+ * If this function throws, the test will not run.
273
+ *
274
+ * @param fn the function to run
275
+ */
276
+ export function beforeEach(fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void)): void;
277
+ /**
278
+ * Runs a function, once, after all the tests.
279
+ *
280
+ * This is useful for running clean up tasks, like closing
281
+ * a socket or deleting temporary files.
282
+ *
283
+ * @example
284
+ * let database;
285
+ * afterAll(async () => {
286
+ * if (database) {
287
+ * await database.close();
288
+ * }
289
+ * });
290
+ *
291
+ * @param fn the function to run
292
+ */
293
+ export function afterAll(fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void)): void;
294
+ /**
295
+ * Runs a function after each test.
296
+ *
297
+ * This is useful for running clean up tasks, like closing
298
+ * a socket or deleting temporary files.
299
+ *
300
+ * @param fn the function to run
301
+ */
302
+ export function afterEach(fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void)): void;
303
+ /**
304
+ * Sets the default timeout for all tests in the current file. If a test specifies a timeout, it will
305
+ * override this value. The default timeout is 5000ms (5 seconds).
306
+ *
307
+ * @param milliseconds the number of milliseconds for the default timeout
308
+ */
309
+ export function setDefaultTimeout(milliseconds: number): void;
310
+ export interface TestOptions {
311
+ /**
312
+ * Sets the timeout for the test in milliseconds.
313
+ *
314
+ * If the test does not complete within this time, the test will fail with:
315
+ * ```ts
316
+ * 'Timeout: test {name} timed out after 5000ms'
317
+ * ```
318
+ *
319
+ * @default 5000 // 5 seconds
320
+ */
321
+ timeout?: number;
322
+ /**
323
+ * Sets the number of times to retry the test if it fails.
324
+ *
325
+ * @default 0
326
+ */
327
+ retry?: number;
328
+ /**
329
+ * Sets the number of times to repeat the test, regardless of whether it passed or failed.
330
+ *
331
+ * @default 0
332
+ */
333
+ repeats?: number;
334
+ }
335
+ /**
336
+ * Runs a test.
337
+ *
338
+ * @example
339
+ * test("can check if using Bun", () => {
340
+ * expect(Bun).toBeDefined();
341
+ * });
342
+ *
343
+ * test("can make a fetch() request", async () => {
344
+ * const response = await fetch("https://example.com/");
345
+ * expect(response.ok).toBe(true);
346
+ * });
347
+ *
348
+ * test("can set a timeout", async () => {
349
+ * await Bun.sleep(100);
350
+ * }, 50); // or { timeout: 50 }
351
+ *
352
+ * @param label the label for the test
353
+ * @param fn the test function
354
+ * @param options the test timeout or options
355
+ */
356
+ export interface Test {
357
+ (
358
+ label: string,
359
+ fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
360
+ /**
361
+ * - If a `number`, sets the timeout for the test in milliseconds.
362
+ * - If an `object`, sets the options for the test.
363
+ * - `timeout` sets the timeout for the test in milliseconds.
364
+ * - `retry` sets the number of times to retry the test if it fails.
365
+ * - `repeats` sets the number of times to repeat the test, regardless of whether it passed or failed.
366
+ */
367
+ options?: number | TestOptions,
368
+ ): void;
369
+ /**
370
+ * Skips all other tests, except this test when run with the `--only` option.
371
+ *
372
+ * @param label the label for the test
373
+ * @param fn the test function
374
+ * @param options the test timeout or options
375
+ */
376
+ only(
377
+ label: string,
378
+ fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
379
+ options?: number | TestOptions,
380
+ ): void;
381
+ /**
382
+ * Skips this test.
383
+ *
384
+ * @param label the label for the test
385
+ * @param fn the test function
386
+ * @param options the test timeout or options
387
+ */
388
+ skip(
389
+ label: string,
390
+ fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
391
+ options?: number | TestOptions,
392
+ ): void;
393
+ /**
394
+ * Marks this test as to be written or to be fixed.
395
+ *
396
+ * These tests will not be executed unless the `--todo` flag is passed. With the flag,
397
+ * if the test passes, the test will be marked as `fail` in the results; you will have to
398
+ * remove the `.todo` or check that your test
399
+ * is implemented correctly.
400
+ *
401
+ * @param label the label for the test
402
+ * @param fn the test function
403
+ * @param options the test timeout or options
404
+ */
405
+ todo(
406
+ label: string,
407
+ fn?: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
408
+ options?: number | TestOptions,
409
+ ): void;
410
+ /**
411
+ * Marks this test as failing.
412
+ *
413
+ * Use `test.failing` when you are writing a test and expecting it to fail.
414
+ * These tests will behave the other way normal tests do. If failing test
415
+ * will throw any errors then it will pass. If it does not throw it will
416
+ * fail.
417
+ *
418
+ * `test.failing` is very similar to {@link test.todo} except that it always
419
+ * runs, regardless of the `--todo` flag.
420
+ *
421
+ * @param label the label for the test
422
+ * @param fn the test function
423
+ */
424
+ failing(label: string, fn?: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void)): void;
425
+ /**
426
+ * Runs this test, if `condition` is true.
427
+ *
428
+ * This is the opposite of `test.skipIf()`.
429
+ *
430
+ * @param condition if the test should run
431
+ */
432
+ if(
433
+ condition: boolean,
434
+ ): (
435
+ label: string,
436
+ fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
437
+ options?: number | TestOptions,
438
+ ) => void;
439
+ /**
440
+ * Skips this test, if `condition` is true.
441
+ *
442
+ * @param condition if the test should be skipped
443
+ */
444
+ skipIf(
445
+ condition: boolean,
446
+ ): (
447
+ label: string,
448
+ fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
449
+ options?: number | TestOptions,
450
+ ) => void;
451
+ /**
452
+ * Marks this test as to be written or to be fixed, if `condition` is true.
453
+ *
454
+ * @param condition if the test should be marked TODO
455
+ */
456
+ todoIf(
457
+ condition: boolean,
458
+ ): (
459
+ label: string,
460
+ fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
461
+ options?: number | TestOptions,
462
+ ) => void;
463
+ /**
464
+ * Returns a function that runs for each item in `table`.
465
+ *
466
+ * @param table Array of Arrays with the arguments that are passed into the test fn for each row.
467
+ */
468
+ each<T extends Readonly<[any, ...any[]]>>(
469
+ table: readonly T[],
470
+ ): (label: string, fn: (...args: [...T]) => void | Promise<unknown>, options?: number | TestOptions) => void;
471
+ each<T extends any[]>(
472
+ table: readonly T[],
473
+ ): (label: string, fn: (...args: Readonly<T>) => void | Promise<unknown>, options?: number | TestOptions) => void;
474
+ each<T>(
475
+ table: T[],
476
+ ): (label: string, fn: (...args: T[]) => void | Promise<unknown>, options?: number | TestOptions) => void;
477
+ }
478
+ /**
479
+ * Runs a test.
480
+ *
481
+ * @example
482
+ * test("can check if using Bun", () => {
483
+ * expect(Bun).toBeDefined();
484
+ * });
485
+ *
486
+ * test("can make a fetch() request", async () => {
487
+ * const response = await fetch("https://example.com/");
488
+ * expect(response.ok).toBe(true);
489
+ * });
490
+ *
491
+ * @param label the label for the test
492
+ * @param fn the test function
493
+ */
494
+ export const test: Test;
495
+ export { test as it };
496
+
497
+ /**
498
+ * Asserts that a value matches some criteria.
499
+ *
500
+ * @link https://jestjs.io/docs/expect#reference
501
+ * @example
502
+ * expect(1 + 1).toBe(2);
503
+ * expect([1,2,3]).toContain(2);
504
+ * expect(null).toBeNull();
505
+ *
506
+ * @param actual The actual (received) value
507
+ */
508
+ export const expect: Expect;
509
+
510
+ type ExpectNot = Omit<AsymmetricMatchers, keyof AsymmetricMatchersBuiltin> & AsymmetricMatchersBuiltinNegated;
511
+
512
+ export interface Expect extends AsymmetricMatchers {
513
+ // the `expect()` callable signature
514
+ /**
515
+ * @param actual the actual value
516
+ * @param customFailMessage an optional custom message to display if the test fails.
517
+ * */
518
+
519
+ <T = unknown>(actual?: T, customFailMessage?: string): Matchers<T>;
520
+
521
+ /**
522
+ * Access to negated asymmetric matchers.
523
+ *
524
+ * @example
525
+ * expect("abc").toEqual(expect.stringContaining("abc")); // will pass
526
+ * expect("abc").toEqual(expect.not.stringContaining("abc")); // will fail
527
+ */
528
+ not: ExpectNot;
529
+
530
+ /**
531
+ * Create an asymmetric matcher for a promise resolved value.
532
+ *
533
+ * @example
534
+ * expect(Promise.resolve("value")).toEqual(expect.resolvesTo.stringContaining("value")); // will pass
535
+ * expect(Promise.reject("value")).toEqual(expect.resolvesTo.stringContaining("value")); // will fail
536
+ * expect("value").toEqual(expect.resolvesTo.stringContaining("value")); // will fail
537
+ */
538
+ resolvesTo: AsymmetricMatchers;
539
+
540
+ /**
541
+ * Create an asymmetric matcher for a promise rejected value.
542
+ *
543
+ * @example
544
+ * expect(Promise.reject("error")).toEqual(expect.rejectsTo.stringContaining("error")); // will pass
545
+ * expect(Promise.resolve("error")).toEqual(expect.rejectsTo.stringContaining("error")); // will fail
546
+ * expect("error").toEqual(expect.rejectsTo.stringContaining("error")); // will fail
547
+ */
548
+ rejectsTo: AsymmetricMatchers;
549
+
550
+ /**
551
+ * Register new custom matchers.
552
+ * @param matchers An object containing the matchers to register, where each key is the matcher name, and its value the implementation function.
553
+ * The function must satisfy: `(actualValue, ...matcherInstantiationArguments) => { pass: true|false, message: () => string }`
554
+ *
555
+ * @example
556
+ * expect.extend({
557
+ * toBeWithinRange(actual, min, max) {
558
+ * if (typeof actual !== 'number' || typeof min !== 'number' || typeof max !== 'number')
559
+ * throw new Error('Invalid usage');
560
+ * const pass = actual >= min && actual <= max;
561
+ * return {
562
+ * pass: pass,
563
+ * message: () => `expected ${this.utils.printReceived(actual)} ` +
564
+ * (pass ? `not to be`: `to be`) + ` within range ${this.utils.printExpected(`${min} .. ${max}`)}`,
565
+ * };
566
+ * },
567
+ * });
568
+ *
569
+ * test('some test', () => {
570
+ * expect(50).toBeWithinRange(0, 100); // will pass
571
+ * expect(50).toBeWithinRange(100, 200); // will fail
572
+ * expect(50).toBe(expect.toBeWithinRange(0, 100)); // will pass
573
+ * expect(50).toBe(expect.not.toBeWithinRange(100, 200)); // will pass
574
+ * });
575
+ */
576
+ extend<M>(matchers: ExpectExtendMatchers<M>): void;
577
+
578
+ /**
579
+ * Throw an error if this function is called.
580
+ *
581
+ * @param msg Optional message to display if the test fails
582
+ * @returns never
583
+ *
584
+ * @example
585
+ * ## Example
586
+ *
587
+ * ```ts
588
+ * import { expect, test } from "bun:test";
589
+ *
590
+ * test("!!abc!! is not a module", () => {
591
+ * try {
592
+ * require("!!abc!!");
593
+ * expect.unreachable();
594
+ * } catch(e) {
595
+ * expect(e.name).not.toBe("UnreachableError");
596
+ * }
597
+ * });
598
+ * ```
599
+ */
600
+ unreachable(msg?: string | Error): never;
601
+
602
+ /**
603
+ * Ensures that an assertion is made
604
+ */
605
+ hasAssertions(): void;
606
+
607
+ /**
608
+ * Ensures that a specific number of assertions are made
609
+ */
610
+ assertions(neededAssertions: number): void;
611
+ }
612
+
613
+ /**
614
+ * You can extend this interface with declaration merging, in order to add type support for custom matchers.
615
+ * @template T Type of the actual value
616
+ *
617
+ * @example
618
+ * // my_modules.d.ts
619
+ * interface MyCustomMatchers {
620
+ * toBeWithinRange(floor: number, ceiling: number): any;
621
+ * }
622
+ * declare module "bun:test" {
623
+ * interface Matchers<T> extends MyCustomMatchers {}
624
+ * interface AsymmetricMatchers extends MyCustomMatchers {}
625
+ * }
626
+ *
627
+ * @example
628
+ * // my_modules.d.ts (alternatively)
629
+ * declare module "bun:test" {
630
+ * interface Matchers<T> {
631
+ * toBeWithinRange(floor: number, ceiling: number): any;
632
+ * }
633
+ * interface AsymmetricMatchers {
634
+ * toBeWithinRange(floor: number, ceiling: number): any;
635
+ * }
636
+ * }
637
+ */
638
+ export interface Matchers<T = unknown> extends MatchersBuiltin<T> {}
639
+
640
+ /**
641
+ * You can extend this interface with declaration merging, in order to add type support for custom asymmetric matchers.
642
+ * @example
643
+ * // my_modules.d.ts
644
+ * interface MyCustomMatchers {
645
+ * toBeWithinRange(floor: number, ceiling: number): any;
646
+ * }
647
+ * declare module "bun:test" {
648
+ * interface Matchers<T> extends MyCustomMatchers {}
649
+ * interface AsymmetricMatchers extends MyCustomMatchers {}
650
+ * }
651
+ *
652
+ * @example
653
+ * // my_modules.d.ts (alternatively)
654
+ * declare module "bun:test" {
655
+ * interface Matchers<T> {
656
+ * toBeWithinRange(floor: number, ceiling: number): any;
657
+ * }
658
+ * interface AsymmetricMatchers {
659
+ * toBeWithinRange(floor: number, ceiling: number): any;
660
+ * }
661
+ * }
662
+ */
663
+ export interface AsymmetricMatchers extends AsymmetricMatchersBuiltin {}
664
+
665
+ export interface AsymmetricMatchersBuiltin {
666
+ /**
667
+ * Matches anything that was created with the given constructor.
668
+ * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
669
+ *
670
+ * @example
671
+ *
672
+ * function randocall(fn) {
673
+ * return fn(Math.floor(Math.random() * 6 + 1));
674
+ * }
675
+ *
676
+ * test('randocall calls its callback with a number', () => {
677
+ * const mock = jest.fn();
678
+ * randocall(mock);
679
+ * expect(mock).toBeCalledWith(expect.any(Number));
680
+ * });
681
+ */
682
+ any(constructor: ((...args: any[]) => any) | { new (...args: any[]): any }): AsymmetricMatcher;
683
+ /**
684
+ * Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead
685
+ * of a literal value. For example, if you want to check that a mock function is called with a
686
+ * non-null argument:
687
+ *
688
+ * @example
689
+ *
690
+ * test('map calls its argument with a non-null argument', () => {
691
+ * const mock = jest.fn();
692
+ * [1].map(x => mock(x));
693
+ * expect(mock).toBeCalledWith(expect.anything());
694
+ * });
695
+ */
696
+ anything(): AsymmetricMatcher;
697
+ /**
698
+ * Matches any array made up entirely of elements in the provided array.
699
+ * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
700
+ *
701
+ * Optionally, you can provide a type for the elements via a generic.
702
+ */
703
+ arrayContaining<E = any>(arr: readonly E[]): AsymmetricMatcher;
704
+ /**
705
+ * Matches any object that recursively matches the provided keys.
706
+ * This is often handy in conjunction with other asymmetric matchers.
707
+ *
708
+ * Optionally, you can provide a type for the object via a generic.
709
+ * This ensures that the object contains the desired structure.
710
+ */
711
+ objectContaining(obj: object): AsymmetricMatcher;
712
+ /**
713
+ * Matches any received string that contains the exact expected string
714
+ */
715
+ stringContaining(str: string | String): AsymmetricMatcher;
716
+ /**
717
+ * Matches any string that contains the exact provided string
718
+ */
719
+ stringMatching(regex: string | String | RegExp): AsymmetricMatcher;
720
+ /**
721
+ * Useful when comparing floating point numbers in object properties or array item.
722
+ * If you need to compare a number, use `.toBeCloseTo` instead.
723
+ *
724
+ * The optional `numDigits` argument limits the number of digits to check after the decimal point.
725
+ * For the default value 2, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`).
726
+ */
727
+ closeTo(num: number, numDigits?: number): AsymmetricMatcher;
728
+ }
729
+
730
+ interface AsymmetricMatchersBuiltinNegated {
731
+ /**
732
+ * Create an asymmetric matcher that will fail on a promise resolved value that matches the chained matcher.
733
+ *
734
+ * @example
735
+ * expect(Promise.resolve("value")).toEqual(expect.not.resolvesTo.stringContaining("value")); // will fail
736
+ * expect(Promise.reject("value")).toEqual(expect.not.resolvesTo.stringContaining("value")); // will pass
737
+ * expect("value").toEqual(expect.not.resolvesTo.stringContaining("value")); // will pass
738
+ */
739
+ resolvesTo: ExpectNot;
740
+
741
+ /**
742
+ * Create an asymmetric matcher that will fail on a promise rejected value that matches the chained matcher.
743
+ *
744
+ * @example
745
+ * expect(Promise.reject("value")).toEqual(expect.not.rejectsTo.stringContaining("value")); // will fail
746
+ * expect(Promise.resolve("value")).toEqual(expect.not.rejectsTo.stringContaining("value")); // will pass
747
+ * expect("value").toEqual(expect.not.rejectsTo.stringContaining("value")); // will pass
748
+ */
749
+ rejectsTo: ExpectNot;
750
+
751
+ /**
752
+ * `expect.not.arrayContaining(array)` matches a received array which
753
+ * does not contain all of the elements in the expected array. That is,
754
+ * the expected array is not a subset of the received array. It is the
755
+ * inverse of `expect.arrayContaining`.
756
+ *
757
+ * Optionally, you can provide a type for the elements via a generic.
758
+ */
759
+ arrayContaining<E = any>(arr: readonly E[]): AsymmetricMatcher;
760
+
761
+ /**
762
+ * `expect.not.objectContaining(object)` matches any received object
763
+ * that does not recursively match the expected properties. That is, the
764
+ * expected object is not a subset of the received object. Therefore,
765
+ * it matches a received object which contains properties that are not
766
+ * in the expected object. It is the inverse of `expect.objectContaining`.
767
+ *
768
+ * Optionally, you can provide a type for the object via a generic.
769
+ * This ensures that the object contains the desired structure.
770
+ */
771
+ objectContaining(obj: object): AsymmetricMatcher;
772
+
773
+ /**
774
+ * `expect.not.stringContaining(string)` matches the received string
775
+ * that does not contain the exact expected string. It is the inverse of
776
+ * `expect.stringContaining`.
777
+ */
778
+ stringContaining(str: string | String): AsymmetricMatcher;
779
+
780
+ /**
781
+ * `expect.not.stringMatching(string | regexp)` matches the received
782
+ * string that does not match the expected regexp. It is the inverse of
783
+ * `expect.stringMatching`.
784
+ */
785
+ stringMatching(str: string | String | RegExp): AsymmetricMatcher;
786
+
787
+ /**
788
+ * `expect.not.closeTo` matches a number not close to the provided value.
789
+ * Useful when comparing floating point numbers in object properties or array item.
790
+ * It is the inverse of `expect.closeTo`.
791
+ */
792
+ closeTo(num: number, numDigits?: number): AsymmetricMatcher;
793
+ }
794
+
795
+ export interface MatchersBuiltin<T = unknown> {
796
+ /**
797
+ * Negates the result of a subsequent assertion.
798
+ * If you know how to test something, `.not` lets you test its opposite.
799
+ *
800
+ * @example
801
+ * expect(1).not.toBe(0);
802
+ * expect(null).not.toBeNull();
803
+ *
804
+ * @example
805
+ * expect(42).toEqual(42); // will pass
806
+ * expect(42).not.toEqual(42); // will fail
807
+ */
808
+ not: Matchers<unknown>;
809
+
810
+ /**
811
+ * Expects the value to be a promise that resolves.
812
+ *
813
+ * @example
814
+ * expect(Promise.resolve(1)).resolves.toBe(1);
815
+ */
816
+ resolves: Matchers<Awaited<T>>;
817
+
818
+ /**
819
+ * Expects the value to be a promise that rejects.
820
+ *
821
+ * @example
822
+ * expect(Promise.reject("error")).rejects.toBe("error");
823
+ */
824
+ rejects: Matchers<unknown>;
825
+
826
+ /**
827
+ * Assertion which passes.
828
+ *
829
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/pass
830
+ * @example
831
+ * expect().pass();
832
+ * expect().pass("message is optional");
833
+ * expect().not.pass();
834
+ * expect().not.pass("hi");
835
+ *
836
+ * @param message the message to display if the test fails (optional)
837
+ */
838
+ pass: (message?: string) => void;
839
+ /**
840
+ * Assertion which fails.
841
+ *
842
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/fail
843
+ * @example
844
+ * expect().fail();
845
+ * expect().fail("message is optional");
846
+ * expect().not.fail();
847
+ * expect().not.fail("hi");
848
+ */
849
+ fail: (message?: string) => void;
850
+ /**
851
+ * Asserts that a value equals what is expected.
852
+ *
853
+ * - For non-primitive values, like objects and arrays,
854
+ * use `toEqual()` instead.
855
+ * - For floating-point numbers, use `toBeCloseTo()` instead.
856
+ *
857
+ * @example
858
+ * expect(100 + 23).toBe(123);
859
+ * expect("d" + "og").toBe("dog");
860
+ * expect([123]).toBe([123]); // fail, use toEqual()
861
+ * expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo()
862
+ *
863
+ * @param expected the expected value
864
+ */
865
+ toBe(expected: T): void;
866
+ /**
867
+ * Asserts that a number is odd.
868
+ *
869
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/number/#tobeodd
870
+ * @example
871
+ * expect(1).toBeOdd();
872
+ * expect(2).not.toBeOdd();
873
+ */
874
+ toBeOdd(): void;
875
+ /**
876
+ * Asserts that a number is even.
877
+ *
878
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/number/#tobeeven
879
+ * @example
880
+ * expect(2).toBeEven();
881
+ * expect(1).not.toBeEven();
882
+ */
883
+ toBeEven(): void;
884
+ /**
885
+ * Asserts that value is close to the expected by floating point precision.
886
+ *
887
+ * For example, the following fails because arithmetic on decimal (base 10)
888
+ * values often have rounding errors in limited precision binary (base 2) representation.
889
+ *
890
+ * @example
891
+ * expect(0.2 + 0.1).toBe(0.3); // fails
892
+ *
893
+ * Use `toBeCloseTo` to compare floating point numbers for approximate equality.
894
+ *
895
+ * @example
896
+ * expect(0.2 + 0.1).toBeCloseTo(0.3, 5); // passes
897
+ *
898
+ * @param expected the expected value
899
+ * @param numDigits the number of digits to check after the decimal point. Default is `2`
900
+ */
901
+ toBeCloseTo(expected: number, numDigits?: number): void;
902
+ /**
903
+ * Asserts that a value is deeply equal to what is expected.
904
+ *
905
+ * @example
906
+ * expect(100 + 23).toBe(123);
907
+ * expect("d" + "og").toBe("dog");
908
+ * expect([456]).toEqual([456]);
909
+ * expect({ value: 1 }).toEqual({ value: 1 });
910
+ *
911
+ * @param expected the expected value
912
+ */
913
+ toEqual(expected: T): void;
914
+ /**
915
+ * Asserts that a value is deeply and strictly equal to
916
+ * what is expected.
917
+ *
918
+ * There are two key differences from `toEqual()`:
919
+ * 1. It checks that the class is the same.
920
+ * 2. It checks that `undefined` values match as well.
921
+ *
922
+ * @example
923
+ * class Dog {
924
+ * type = "dog";
925
+ * }
926
+ * const actual = new Dog();
927
+ * expect(actual).toStrictEqual(new Dog());
928
+ * expect(actual).toStrictEqual({ type: "dog" }); // fail
929
+ *
930
+ * @example
931
+ * const actual = { value: 1, name: undefined };
932
+ * expect(actual).toEqual({ value: 1 });
933
+ * expect(actual).toStrictEqual({ value: 1 }); // fail
934
+ *
935
+ * @param expected the expected value
936
+ */
937
+ toStrictEqual(expected: T): void;
938
+ /**
939
+ * Asserts that the value is deep equal to an element in the expected array.
940
+ *
941
+ * The value must be an array or iterable, which includes strings.
942
+ *
943
+ * @example
944
+ * expect(1).toBeOneOf([1,2,3]);
945
+ * expect("foo").toBeOneOf(["foo", "bar"]);
946
+ * expect(true).toBeOneOf(new Set([true]));
947
+ *
948
+ * @param expected the expected value
949
+ */
950
+ toBeOneOf(expected: Array<unknown> | Iterable<unknown>): void;
951
+ /**
952
+ * Asserts that a value contains what is expected.
953
+ *
954
+ * The value must be an array or iterable, which
955
+ * includes strings.
956
+ *
957
+ * @example
958
+ * expect([1, 2, 3]).toContain(1);
959
+ * expect(new Set([true])).toContain(true);
960
+ * expect("hello").toContain("o");
961
+ *
962
+ * @param expected the expected value
963
+ */
964
+ toContain(expected: unknown): void;
965
+ /**
966
+ * Asserts that an `object` contains a key.
967
+ *
968
+ * The value must be an object
969
+ *
970
+ * @example
971
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKey('a');
972
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKey('b');
973
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKey('c');
974
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).not.toContainKey('d');
975
+ *
976
+ * @param expected the expected value
977
+ */
978
+ toContainKey(expected: unknown): void;
979
+ /**
980
+ * Asserts that an `object` contains all the provided keys.
981
+ *
982
+ * The value must be an object
983
+ *
984
+ * @example
985
+ * expect({ a: 'hello', b: 'world' }).toContainAllKeys(['a','b']);
986
+ * expect({ a: 'hello', b: 'world' }).toContainAllKeys(['b','a']);
987
+ * expect({ 1: 'hello', b: 'world' }).toContainAllKeys([1,'b']);
988
+ * expect({ a: 'hello', b: 'world' }).not.toContainAllKeys(['c']);
989
+ * expect({ a: 'hello', b: 'world' }).not.toContainAllKeys(['a']);
990
+ *
991
+ * @param expected the expected value
992
+ */
993
+ toContainAllKeys(expected: unknown): void;
994
+ /**
995
+ * Asserts that an `object` contains at least one of the provided keys.
996
+ * Asserts that an `object` contains all the provided keys.
997
+ *
998
+ * The value must be an object
999
+ *
1000
+ * @example
1001
+ * expect({ a: 'hello', b: 'world' }).toContainAnyKeys(['a']);
1002
+ * expect({ a: 'hello', b: 'world' }).toContainAnyKeys(['b']);
1003
+ * expect({ a: 'hello', b: 'world' }).toContainAnyKeys(['b', 'c']);
1004
+ * expect({ a: 'hello', b: 'world' }).not.toContainAnyKeys(['c']);
1005
+ *
1006
+ * @param expected the expected value
1007
+ */
1008
+ toContainAnyKeys(expected: unknown): void;
1009
+
1010
+ /**
1077
1011
  * Asserts that an `object` contain the provided value.
1078
1012
  *
1079
1013
  * The value must be an object
@@ -1100,1189 +1034,1144 @@ declare module "bun:test" {
1100
1034
  *
1101
1035
  * @param expected the expected value
1102
1036
  */
1103
- toContainValue(expected: unknown): void;
1104
-
1105
- /**
1106
- * Asserts that an `object` contain the provided value.
1107
- *
1108
- * The value must be an object
1109
- *
1110
- * @example
1111
- * const o = { a: 'foo', b: 'bar', c: 'baz' };
1112
- * expect(o).toContainValues(['foo']);
1113
- * expect(o).toContainValues(['baz', 'bar']);
1114
- * expect(o).not.toContainValues(['qux', 'foo']);
1115
- * @param expected the expected value
1116
- */
1117
- toContainValues(expected: unknown): void;
1118
-
1119
- /**
1120
- * Asserts that an `object` contain all the provided values.
1121
- *
1122
- * The value must be an object
1123
- *
1124
- * @example
1125
- * const o = { a: 'foo', b: 'bar', c: 'baz' };
1126
- * expect(o).toContainAllValues(['foo', 'bar', 'baz']);
1127
- * expect(o).toContainAllValues(['baz', 'bar', 'foo']);
1128
- * expect(o).not.toContainAllValues(['bar', 'foo']);
1129
- * @param expected the expected value
1130
- */
1131
- toContainAllValues(expected: unknown): void;
1132
-
1133
- /**
1134
- * Asserts that an `object` contain any provided value.
1135
- *
1136
- * The value must be an object
1137
- *
1138
- * @example
1139
- * const o = { a: 'foo', b: 'bar', c: 'baz' };
1140
- * expect(o).toContainAnyValues(['qux', 'foo']);
1141
- * expect(o).toContainAnyValues(['qux', 'bar']);
1142
- * expect(o).toContainAnyValues(['qux', 'baz']);
1143
- * expect(o).not.toContainAnyValues(['qux']);
1144
- * @param expected the expected value
1145
- */
1146
- toContainAnyValues(expected: unknown): void;
1147
-
1148
- /**
1149
- * Asserts that an `object` contains all the provided keys.
1150
- *
1151
- * @example
1152
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKeys(['a', 'b']);
1153
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKeys(['a', 'b', 'c']);
1154
- * expect({ a: 'foo', b: 'bar', c: 'baz' }).not.toContainKeys(['a', 'b', 'e']);
1155
- *
1156
- * @param expected the expected value
1157
- */
1158
- toContainKeys(expected: unknown): void;
1159
- /**
1160
- * Asserts that a value contains and equals what is expected.
1161
- *
1162
- * This matcher will perform a deep equality check for members
1163
- * of arrays, rather than checking for object identity.
1164
- *
1165
- * @example
1166
- * expect([{ a: 1 }]).toContainEqual({ a: 1 });
1167
- * expect([{ a: 1 }]).not.toContainEqual({ a: 2 });
1168
- *
1169
- * @param expected the expected value
1170
- */
1171
- toContainEqual(expected: unknown): void;
1172
- /**
1173
- * Asserts that a value has a `.length` property
1174
- * that is equal to the expected length.
1175
- *
1176
- * @example
1177
- * expect([]).toHaveLength(0);
1178
- * expect("hello").toHaveLength(4);
1179
- *
1180
- * @param length the expected length
1181
- */
1182
- toHaveLength(length: number): void;
1183
- /**
1184
- * Asserts that a value has a property with the
1185
- * expected name, and value if provided.
1186
- *
1187
- * @example
1188
- * expect(new Set()).toHaveProperty("size");
1189
- * expect(new Uint8Array()).toHaveProperty("byteLength", 0);
1190
- * expect({ kitchen: { area: 20 }}).toHaveProperty("kitchen.area", 20);
1191
- * expect({ kitchen: { area: 20 }}).toHaveProperty(["kitchen", "area"], 20);
1192
- *
1193
- * @param keyPath the expected property name or path, or an index
1194
- * @param value the expected property value, if provided
1195
- */
1196
- toHaveProperty(
1197
- keyPath: string | number | Array<string | number>,
1198
- value?: unknown,
1199
- ): void;
1200
- /**
1201
- * Asserts that a value is "truthy".
1202
- *
1203
- * To assert that a value equals `true`, use `toBe(true)` instead.
1204
- *
1205
- * @link https://developer.mozilla.org/en-US/docs/Glossary/Truthy
1206
- * @example
1207
- * expect(true).toBeTruthy();
1208
- * expect(1).toBeTruthy();
1209
- * expect({}).toBeTruthy();
1210
- */
1211
- toBeTruthy(): void;
1212
- /**
1213
- * Asserts that a value is "falsy".
1214
- *
1215
- * To assert that a value equals `false`, use `toBe(false)` instead.
1216
- *
1217
- * @link https://developer.mozilla.org/en-US/docs/Glossary/Falsy
1218
- * @example
1219
- * expect(true).toBeTruthy();
1220
- * expect(1).toBeTruthy();
1221
- * expect({}).toBeTruthy();
1222
- */
1223
- toBeFalsy(): void;
1224
- /**
1225
- * Asserts that a value is defined. (e.g. is not `undefined`)
1226
- *
1227
- * @example
1228
- * expect(true).toBeDefined();
1229
- * expect(undefined).toBeDefined(); // fail
1230
- */
1231
- toBeDefined(): void;
1232
- /**
1233
- * Asserts that the expected value is an instance of value
1234
- *
1235
- * @example
1236
- * expect([]).toBeInstanceOf(Array);
1237
- * expect(null).toBeInstanceOf(Array); // fail
1238
- */
1239
- toBeInstanceOf(value: unknown): void;
1240
- /**
1241
- * Asserts that the expected value is an instance of value
1242
- *
1243
- * @example
1244
- * expect([]).toBeInstanceOf(Array);
1245
- * expect(null).toBeInstanceOf(Array); // fail
1246
- */
1247
- toBeInstanceOf(value: unknown): void;
1248
- /**
1249
- * Asserts that a value is `undefined`.
1250
- *
1251
- * @example
1252
- * expect(undefined).toBeUndefined();
1253
- * expect(null).toBeUndefined(); // fail
1254
- */
1255
- toBeUndefined(): void;
1256
- /**
1257
- * Asserts that a value is `null`.
1258
- *
1259
- * @example
1260
- * expect(null).toBeNull();
1261
- * expect(undefined).toBeNull(); // fail
1262
- */
1263
- toBeNull(): void;
1264
- /**
1265
- * Asserts that a value is `NaN`.
1266
- *
1267
- * Same as using `Number.isNaN()`.
1268
- *
1269
- * @example
1270
- * expect(NaN).toBeNaN();
1271
- * expect(Infinity).toBeNaN(); // fail
1272
- * expect("notanumber").toBeNaN(); // fail
1273
- */
1274
- toBeNaN(): void;
1275
- /**
1276
- * Asserts that a value is a `number` and is greater than the expected value.
1277
- *
1278
- * @example
1279
- * expect(1).toBeGreaterThan(0);
1280
- * expect(3.14).toBeGreaterThan(3);
1281
- * expect(9).toBeGreaterThan(9); // fail
1282
- *
1283
- * @param expected the expected number
1284
- */
1285
- toBeGreaterThan(expected: number | bigint): void;
1286
- /**
1287
- * Asserts that a value is a `number` and is greater than or equal to the expected value.
1288
- *
1289
- * @example
1290
- * expect(1).toBeGreaterThanOrEqual(0);
1291
- * expect(3.14).toBeGreaterThanOrEqual(3);
1292
- * expect(9).toBeGreaterThanOrEqual(9);
1293
- *
1294
- * @param expected the expected number
1295
- */
1296
- toBeGreaterThanOrEqual(expected: number | bigint): void;
1297
- /**
1298
- * Asserts that a value is a `number` and is less than the expected value.
1299
- *
1300
- * @example
1301
- * expect(-1).toBeLessThan(0);
1302
- * expect(3).toBeLessThan(3.14);
1303
- * expect(9).toBeLessThan(9); // fail
1304
- *
1305
- * @param expected the expected number
1306
- */
1307
- toBeLessThan(expected: number | bigint): void;
1308
- /**
1309
- * Asserts that a value is a `number` and is less than or equal to the expected value.
1310
- *
1311
- * @example
1312
- * expect(-1).toBeLessThanOrEqual(0);
1313
- * expect(3).toBeLessThanOrEqual(3.14);
1314
- * expect(9).toBeLessThanOrEqual(9);
1315
- *
1316
- * @param expected the expected number
1317
- */
1318
- toBeLessThanOrEqual(expected: number | bigint): void;
1319
- /**
1320
- * Asserts that a function throws an error.
1321
- *
1322
- * - If expected is a `string` or `RegExp`, it will check the `message` property.
1323
- * - If expected is an `Error` object, it will check the `name` and `message` properties.
1324
- * - If expected is an `Error` constructor, it will check the class of the `Error`.
1325
- * - If expected is not provided, it will check if anything has thrown.
1326
- *
1327
- * @example
1328
- * function fail() {
1329
- * throw new Error("Oops!");
1330
- * }
1331
- * expect(fail).toThrow("Oops!");
1332
- * expect(fail).toThrow(/oops/i);
1333
- * expect(fail).toThrow(Error);
1334
- * expect(fail).toThrow();
1335
- *
1336
- * @param expected the expected error, error message, or error pattern
1337
- */
1338
- toThrow(expected?: unknown): void;
1339
- /**
1340
- * Asserts that a function throws an error.
1341
- *
1342
- * - If expected is a `string` or `RegExp`, it will check the `message` property.
1343
- * - If expected is an `Error` object, it will check the `name` and `message` properties.
1344
- * - If expected is an `Error` constructor, it will check the class of the `Error`.
1345
- * - If expected is not provided, it will check if anything has thrown.
1346
- *
1347
- * @example
1348
- * function fail() {
1349
- * throw new Error("Oops!");
1350
- * }
1351
- * expect(fail).toThrowError("Oops!");
1352
- * expect(fail).toThrowError(/oops/i);
1353
- * expect(fail).toThrowError(Error);
1354
- * expect(fail).toThrowError();
1355
- *
1356
- * @param expected the expected error, error message, or error pattern
1357
- * @alias toThrow
1358
- */
1359
- toThrowError(expected?: unknown): void;
1360
- /**
1361
- * Asserts that a value matches a regular expression or includes a substring.
1362
- *
1363
- * @example
1364
- * expect("dog").toMatch(/dog/);
1365
- * expect("dog").toMatch("og");
1366
- *
1367
- * @param expected the expected substring or pattern.
1368
- */
1369
- toMatch(expected: string | RegExp): void;
1370
- /**
1371
- * Asserts that a value matches the most recent snapshot.
1372
- *
1373
- * @example
1374
- * expect([1, 2, 3]).toMatchSnapshot('hint message');
1375
- * @param hint Hint used to identify the snapshot in the snapshot file.
1376
- */
1377
- toMatchSnapshot(hint?: string): void;
1378
- /**
1379
- * Asserts that a value matches the most recent snapshot.
1380
- *
1381
- * @example
1382
- * expect([1, 2, 3]).toMatchSnapshot();
1383
- * expect({ a: 1, b: 2 }).toMatchSnapshot({ a: 1 });
1384
- * expect({ c: new Date() }).toMatchSnapshot({ c: expect.any(Date) });
1385
- *
1386
- * @param propertyMatchers Object containing properties to match against the value.
1387
- * @param hint Hint used to identify the snapshot in the snapshot file.
1388
- */
1389
- toMatchSnapshot(propertyMatchers?: object, hint?: string): void;
1390
- /**
1391
- * Asserts that a value matches the most recent inline snapshot.
1392
- *
1393
- * @example
1394
- * expect("Hello").toMatchInlineSnapshot();
1395
- * expect("Hello").toMatchInlineSnapshot(`"Hello"`);
1396
- *
1397
- * @param value The latest automatically-updated snapshot value.
1398
- */
1399
- toMatchInlineSnapshot(value?: string): void;
1400
- /**
1401
- * Asserts that a value matches the most recent inline snapshot.
1402
- *
1403
- * @example
1404
- * expect({ c: new Date() }).toMatchInlineSnapshot({ c: expect.any(Date) });
1405
- * expect({ c: new Date() }).toMatchInlineSnapshot({ c: expect.any(Date) }, `
1406
- * {
1407
- * "v": Any<Date>,
1408
- * }
1409
- * `);
1410
- *
1411
- * @param propertyMatchers Object containing properties to match against the value.
1412
- * @param value The latest automatically-updated snapshot value.
1413
- */
1414
- toMatchInlineSnapshot(propertyMatchers?: object, value?: string): void;
1415
- /**
1416
- * Asserts that a function throws an error matching the most recent snapshot.
1417
- *
1418
- * @example
1419
- * function fail() {
1420
- * throw new Error("Oops!");
1421
- * }
1422
- * expect(fail).toThrowErrorMatchingSnapshot();
1423
- * expect(fail).toThrowErrorMatchingSnapshot("This one should say Oops!");
1424
- *
1425
- * @param value The latest automatically-updated snapshot value.
1426
- */
1427
- toThrowErrorMatchingSnapshot(hint?: string): void;
1428
- /**
1429
- * Asserts that a function throws an error matching the most recent snapshot.
1430
- *
1431
- * @example
1432
- * function fail() {
1433
- * throw new Error("Oops!");
1434
- * }
1435
- * expect(fail).toThrowErrorMatchingInlineSnapshot();
1436
- * expect(fail).toThrowErrorMatchingInlineSnapshot(`"Oops!"`);
1437
- *
1438
- * @param value The latest automatically-updated snapshot value.
1439
- */
1440
- toThrowErrorMatchingInlineSnapshot(value?: string): void;
1441
- /**
1442
- * Asserts that an object matches a subset of properties.
1443
- *
1444
- * @example
1445
- * expect({ a: 1, b: 2 }).toMatchObject({ b: 2 });
1446
- * expect({ c: new Date(), d: 2 }).toMatchObject({ d: 2 });
1447
- *
1448
- * @param subset Subset of properties to match with.
1449
- */
1450
- toMatchObject(subset: object): void;
1451
- /**
1452
- * Asserts that a value is empty.
1453
- *
1454
- * @example
1455
- * expect("").toBeEmpty();
1456
- * expect([]).toBeEmpty();
1457
- * expect({}).toBeEmpty();
1458
- * expect(new Set()).toBeEmpty();
1459
- */
1460
- toBeEmpty(): void;
1461
- /**
1462
- * Asserts that a value is an empty `object`.
1463
- *
1464
- * @example
1465
- * expect({}).toBeEmptyObject();
1466
- * expect({ a: 'hello' }).not.toBeEmptyObject();
1467
- */
1468
- toBeEmptyObject(): void;
1469
- /**
1470
- * Asserts that a value is `null` or `undefined`.
1471
- *
1472
- * @example
1473
- * expect(null).toBeNil();
1474
- * expect(undefined).toBeNil();
1475
- */
1476
- toBeNil(): void;
1477
- /**
1478
- * Asserts that a value is a `array`.
1479
- *
1480
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/array/#tobearray
1481
- * @example
1482
- * expect([1]).toBeArray();
1483
- * expect(new Array(1)).toBeArray();
1484
- * expect({}).not.toBeArray();
1485
- */
1486
- toBeArray(): void;
1487
- /**
1488
- * Asserts that a value is a `array` of a certain length.
1489
- *
1490
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/array/#tobearrayofsize
1491
- * @example
1492
- * expect([]).toBeArrayOfSize(0);
1493
- * expect([1]).toBeArrayOfSize(1);
1494
- * expect(new Array(1)).toBeArrayOfSize(1);
1495
- * expect({}).not.toBeArrayOfSize(0);
1496
- */
1497
- toBeArrayOfSize(size: number): void;
1498
- /**
1499
- * Asserts that a value is a `boolean`.
1500
- *
1501
- * @example
1502
- * expect(true).toBeBoolean();
1503
- * expect(false).toBeBoolean();
1504
- * expect(null).not.toBeBoolean();
1505
- * expect(0).not.toBeBoolean();
1506
- */
1507
- toBeBoolean(): void;
1508
- /**
1509
- * Asserts that a value is `true`.
1510
- *
1511
- * @example
1512
- * expect(true).toBeTrue();
1513
- * expect(false).not.toBeTrue();
1514
- * expect(1).not.toBeTrue();
1515
- */
1516
- toBeTrue(): void;
1517
- /**
1518
- * Asserts that a value matches a specific type.
1519
- *
1520
- * @link https://vitest.dev/api/expect.html#tobetypeof
1521
- * @example
1522
- * expect(1).toBeTypeOf("number");
1523
- * expect("hello").toBeTypeOf("string");
1524
- * expect([]).not.toBeTypeOf("boolean");
1525
- */
1526
- toBeTypeOf(
1527
- type:
1528
- | "bigint"
1529
- | "boolean"
1530
- | "function"
1531
- | "number"
1532
- | "object"
1533
- | "string"
1534
- | "symbol"
1535
- | "undefined",
1536
- ): void;
1537
- /**
1538
- * Asserts that a value is `false`.
1539
- *
1540
- * @example
1541
- * expect(false).toBeFalse();
1542
- * expect(true).not.toBeFalse();
1543
- * expect(0).not.toBeFalse();
1544
- */
1545
- toBeFalse(): void;
1546
- /**
1547
- * Asserts that a value is a `number`.
1548
- *
1549
- * @example
1550
- * expect(1).toBeNumber();
1551
- * expect(3.14).toBeNumber();
1552
- * expect(NaN).toBeNumber();
1553
- * expect(BigInt(1)).not.toBeNumber();
1554
- */
1555
- toBeNumber(): void;
1556
- /**
1557
- * Asserts that a value is a `number`, and is an integer.
1558
- *
1559
- * @example
1560
- * expect(1).toBeInteger();
1561
- * expect(3.14).not.toBeInteger();
1562
- * expect(NaN).not.toBeInteger();
1563
- */
1564
- toBeInteger(): void;
1565
- /**
1566
- * Asserts that a value is an `object`.
1567
- *
1568
- * @example
1569
- * expect({}).toBeObject();
1570
- * expect("notAnObject").not.toBeObject();
1571
- * expect(NaN).not.toBeObject();
1572
- */
1573
- toBeObject(): void;
1574
- /**
1575
- * Asserts that a value is a `number`, and is not `NaN` or `Infinity`.
1576
- *
1577
- * @example
1578
- * expect(1).toBeFinite();
1579
- * expect(3.14).toBeFinite();
1580
- * expect(NaN).not.toBeFinite();
1581
- * expect(Infinity).not.toBeFinite();
1582
- */
1583
- toBeFinite(): void;
1584
- /**
1585
- * Asserts that a value is a positive `number`.
1586
- *
1587
- * @example
1588
- * expect(1).toBePositive();
1589
- * expect(-3.14).not.toBePositive();
1590
- * expect(NaN).not.toBePositive();
1591
- */
1592
- toBePositive(): void;
1593
- /**
1594
- * Asserts that a value is a negative `number`.
1595
- *
1596
- * @example
1597
- * expect(-3.14).toBeNegative();
1598
- * expect(1).not.toBeNegative();
1599
- * expect(NaN).not.toBeNegative();
1600
- */
1601
- toBeNegative(): void;
1602
- /**
1603
- * Asserts that a value is a number between a start and end value.
1604
- *
1605
- * @param start the start number (inclusive)
1606
- * @param end the end number (exclusive)
1607
- */
1608
- toBeWithin(start: number, end: number): void;
1609
- /**
1610
- * Asserts that a value is equal to the expected string, ignoring any whitespace.
1611
- *
1612
- * @example
1613
- * expect(" foo ").toEqualIgnoringWhitespace("foo");
1614
- * expect("bar").toEqualIgnoringWhitespace(" bar ");
1615
- *
1616
- * @param expected the expected string
1617
- */
1618
- toEqualIgnoringWhitespace(expected: string): void;
1619
- /**
1620
- * Asserts that a value is a `symbol`.
1621
- *
1622
- * @example
1623
- * expect(Symbol("foo")).toBeSymbol();
1624
- * expect("foo").not.toBeSymbol();
1625
- */
1626
- toBeSymbol(): void;
1627
- /**
1628
- * Asserts that a value is a `function`.
1629
- *
1630
- * @example
1631
- * expect(() => {}).toBeFunction();
1632
- */
1633
- toBeFunction(): void;
1634
- /**
1635
- * Asserts that a value is a `Date` object.
1636
- *
1637
- * To check if a date is valid, use `toBeValidDate()` instead.
1638
- *
1639
- * @example
1640
- * expect(new Date()).toBeDate();
1641
- * expect(new Date(null)).toBeDate();
1642
- * expect("2020-03-01").not.toBeDate();
1643
- */
1644
- toBeDate(): void;
1645
- /**
1646
- * Asserts that a value is a valid `Date` object.
1647
- *
1648
- * @example
1649
- * expect(new Date()).toBeValidDate();
1650
- * expect(new Date(null)).not.toBeValidDate();
1651
- * expect("2020-03-01").not.toBeValidDate();
1652
- */
1653
- toBeValidDate(): void;
1654
- /**
1655
- * Asserts that a value is a `string`.
1656
- *
1657
- * @example
1658
- * expect("foo").toBeString();
1659
- * expect(new String("bar")).toBeString();
1660
- * expect(123).not.toBeString();
1661
- */
1662
- toBeString(): void;
1663
- /**
1664
- * Asserts that a value includes a `string`.
1665
- *
1666
- * For non-string values, use `toContain()` instead.
1667
- *
1668
- * @param expected the expected substring
1669
- */
1670
- toInclude(expected: string): void;
1671
- /**
1672
- * Asserts that a value includes a `string` {times} times.
1673
- * @param expected the expected substring
1674
- * @param times the number of times the substring should occur
1675
- */
1676
- toIncludeRepeated(expected: string, times: number): void;
1677
- /**
1678
- * Checks whether a value satisfies a custom condition.
1679
- * @param {Function} predicate - The custom condition to be satisfied. It should be a function that takes a value as an argument (in this case the value from expect) and returns a boolean.
1680
- * @example
1681
- * expect(1).toSatisfy((val) => val > 0);
1682
- * expect("foo").toSatisfy((val) => val === "foo");
1683
- * expect("bar").not.toSatisfy((val) => val === "bun");
1684
- * @link https://vitest.dev/api/expect.html#tosatisfy
1685
- * @link https://jest-extended.jestcommunity.dev/docs/matchers/toSatisfy
1686
- */
1687
- toSatisfy(predicate: (value: T) => boolean): void;
1688
- /**
1689
- * Asserts that a value starts with a `string`.
1690
- *
1691
- * @param expected the string to start with
1692
- */
1693
- toStartWith(expected: string): void;
1694
- /**
1695
- * Asserts that a value ends with a `string`.
1696
- *
1697
- * @param expected the string to end with
1698
- */
1699
- toEndWith(expected: string): void;
1700
- /**
1701
- * Ensures that a mock function has returned successfully at least once.
1702
- *
1703
- * A promise that is unfulfilled will be considered a failure. If the
1704
- * function threw an error, it will be considered a failure.
1705
- */
1706
- toHaveReturned(): void;
1707
-
1708
- /**
1709
- * Ensures that a mock function has returned successfully at `times` times.
1710
- *
1711
- * A promise that is unfulfilled will be considered a failure. If the
1712
- * function threw an error, it will be considered a failure.
1713
- */
1714
- toHaveReturnedTimes(times: number): void;
1715
-
1716
- /**
1717
- * Ensures that a mock function is called.
1718
- */
1719
- toHaveBeenCalled(): void;
1720
- /**
1721
- * Ensures that a mock function is called an exact number of times.
1722
- * @alias toHaveBeenCalled
1723
- */
1724
- toBeCalled(): void;
1725
- /**
1726
- * Ensures that a mock function is called an exact number of times.
1727
- */
1728
- toHaveBeenCalledTimes(expected: number): void;
1729
- /**
1730
- * Ensure that a mock function is called with specific arguments.
1731
- * @alias toHaveBeenCalledTimes
1732
- */
1733
- toBeCalledTimes(expected: number): void;
1734
- /**
1735
- * Ensure that a mock function is called with specific arguments.
1736
- */
1737
- toHaveBeenCalledWith(...expected: unknown[]): void;
1738
- /**
1739
- * Ensure that a mock function is called with specific arguments.
1740
- * @alias toHaveBeenCalledWith
1741
- */
1742
- toBeCalledWith(...expected: unknown[]): void;
1743
- /**
1744
- * Ensure that a mock function is called with specific arguments for the last call.
1745
- */
1746
- toHaveBeenLastCalledWith(...expected: unknown[]): void;
1747
- /**
1748
- * Ensure that a mock function is called with specific arguments for the nth call.
1749
- * @alias toHaveBeenCalledWith
1750
- */
1751
- lastCalledWith(...expected: unknown[]): void;
1752
- /**
1753
- * Ensure that a mock function is called with specific arguments for the nth call.
1754
- */
1755
- toHaveBeenNthCalledWith(n: number, ...expected: unknown[]): void;
1756
- /**
1757
- * Ensure that a mock function is called with specific arguments for the nth call.
1758
- * @alias toHaveBeenCalledWith
1759
- */
1760
- nthCalledWith(n: number, ...expected: unknown[]): void;
1761
- }
1762
-
1763
- /**
1764
- * Object representing an asymmetric matcher obtained by an static call to expect like `expect.anything()`, `expect.stringContaining("...")`, etc.
1765
- */
1766
- // Defined as an alias of `any` so that it does not trigger any type mismatch
1767
- export type AsymmetricMatcher = any;
1768
-
1769
- export interface MatcherResult {
1770
- pass: boolean;
1771
- message?: string | (() => string);
1772
- }
1773
-
1774
- export type CustomMatcher<E, P extends any[]> = (
1775
- this: MatcherContext,
1776
- expected: E,
1777
- ...matcherArguments: P
1778
- ) => MatcherResult | Promise<MatcherResult>;
1779
-
1780
- /** All non-builtin matchers and asymmetric matchers that have been type-registered through declaration merging */
1781
- export type CustomMatchersDetected = Omit<
1782
- Matchers<unknown>,
1783
- keyof MatchersBuiltin<unknown>
1784
- > &
1785
- Omit<AsymmetricMatchers, keyof AsymmetricMatchersBuiltin>;
1786
-
1787
- /**
1788
- * If the types has been defined through declaration merging, enforce it.
1789
- * Otherwise enforce the generic custom matcher signature.
1790
- */
1791
- export type ExpectExtendMatchers<M> = {
1792
- [k in keyof M]: k extends keyof CustomMatchersDetected
1793
- ? CustomMatcher<unknown, Parameters<CustomMatchersDetected[k]>>
1794
- : CustomMatcher<unknown, any[]>;
1795
- };
1796
-
1797
- /** Custom equality tester */
1798
- export type Tester = (
1799
- this: TesterContext,
1800
- a: any,
1801
- b: any,
1802
- customTesters: Tester[],
1803
- ) => boolean | undefined;
1804
-
1805
- export type EqualsFunction = (
1806
- a: unknown,
1807
- b: unknown,
1808
- //customTesters?: Array<Tester>,
1809
- //strictCheck?: boolean,
1810
- ) => boolean;
1811
-
1812
- export interface TesterContext {
1813
- equals: EqualsFunction;
1814
- }
1815
-
1816
- interface MatcherState {
1817
- //assertionCalls: number;
1818
- //currentConcurrentTestName?: () => string | undefined;
1819
- //currentTestName?: string;
1820
- //error?: Error;
1821
- //expand: boolean;
1822
- //expectedAssertionsNumber: number | null;
1823
- //expectedAssertionsNumberError?: Error;
1824
- //isExpectingAssertions: boolean;
1825
- //isExpectingAssertionsError?: Error;
1826
- isNot: boolean;
1827
- //numPassingAsserts: number;
1828
- promise: string;
1829
- //suppressedErrors: Array<Error>;
1830
- //testPath?: string;
1831
- }
1832
-
1833
- type MatcherHintColor = (arg: string) => string; // subset of Chalk type
1834
-
1835
- interface MatcherUtils {
1836
- //customTesters: Array<Tester>;
1837
- //dontThrow(): void; // (internally used by jest snapshot)
1838
- equals: EqualsFunction;
1839
- utils: Readonly<{
1840
- stringify(value: unknown): string;
1841
- printReceived(value: unknown): string;
1842
- printExpected(value: unknown): string;
1843
- matcherHint(
1844
- matcherName: string,
1845
- received?: unknown,
1846
- expected?: unknown,
1847
- options?: {
1848
- isNot?: boolean;
1849
- promise?: string;
1850
- isDirectExpectCall?: boolean; // (internal)
1851
- comment?: string;
1852
- expectedColor?: MatcherHintColor;
1853
- receivedColor?: MatcherHintColor;
1854
- secondArgument?: string;
1855
- secondArgumentColor?: MatcherHintColor;
1856
- },
1857
- ): string;
1858
- //iterableEquality: Tester;
1859
- //subsetEquality: Tester;
1860
- // ...
1861
- }>;
1862
- }
1863
-
1864
- type MatcherContext = MatcherUtils & MatcherState;
1865
- }
1037
+ toContainValue(expected: unknown): void;
1038
+
1039
+ /**
1040
+ * Asserts that an `object` contain the provided value.
1041
+ *
1042
+ * The value must be an object
1043
+ *
1044
+ * @example
1045
+ * const o = { a: 'foo', b: 'bar', c: 'baz' };
1046
+ * expect(o).toContainValues(['foo']);
1047
+ * expect(o).toContainValues(['baz', 'bar']);
1048
+ * expect(o).not.toContainValues(['qux', 'foo']);
1049
+ * @param expected the expected value
1050
+ */
1051
+ toContainValues(expected: unknown): void;
1052
+
1053
+ /**
1054
+ * Asserts that an `object` contain all the provided values.
1055
+ *
1056
+ * The value must be an object
1057
+ *
1058
+ * @example
1059
+ * const o = { a: 'foo', b: 'bar', c: 'baz' };
1060
+ * expect(o).toContainAllValues(['foo', 'bar', 'baz']);
1061
+ * expect(o).toContainAllValues(['baz', 'bar', 'foo']);
1062
+ * expect(o).not.toContainAllValues(['bar', 'foo']);
1063
+ * @param expected the expected value
1064
+ */
1065
+ toContainAllValues(expected: unknown): void;
1066
+
1067
+ /**
1068
+ * Asserts that an `object` contain any provided value.
1069
+ *
1070
+ * The value must be an object
1071
+ *
1072
+ * @example
1073
+ * const o = { a: 'foo', b: 'bar', c: 'baz' };
1074
+ * expect(o).toContainAnyValues(['qux', 'foo']);
1075
+ * expect(o).toContainAnyValues(['qux', 'bar']);
1076
+ * expect(o).toContainAnyValues(['qux', 'baz']);
1077
+ * expect(o).not.toContainAnyValues(['qux']);
1078
+ * @param expected the expected value
1079
+ */
1080
+ toContainAnyValues(expected: unknown): void;
1081
+
1082
+ /**
1083
+ * Asserts that an `object` contains all the provided keys.
1084
+ *
1085
+ * @example
1086
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKeys(['a', 'b']);
1087
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).toContainKeys(['a', 'b', 'c']);
1088
+ * expect({ a: 'foo', b: 'bar', c: 'baz' }).not.toContainKeys(['a', 'b', 'e']);
1089
+ *
1090
+ * @param expected the expected value
1091
+ */
1092
+ toContainKeys(expected: unknown): void;
1093
+ /**
1094
+ * Asserts that a value contains and equals what is expected.
1095
+ *
1096
+ * This matcher will perform a deep equality check for members
1097
+ * of arrays, rather than checking for object identity.
1098
+ *
1099
+ * @example
1100
+ * expect([{ a: 1 }]).toContainEqual({ a: 1 });
1101
+ * expect([{ a: 1 }]).not.toContainEqual({ a: 2 });
1102
+ *
1103
+ * @param expected the expected value
1104
+ */
1105
+ toContainEqual(expected: unknown): void;
1106
+ /**
1107
+ * Asserts that a value has a `.length` property
1108
+ * that is equal to the expected length.
1109
+ *
1110
+ * @example
1111
+ * expect([]).toHaveLength(0);
1112
+ * expect("hello").toHaveLength(4);
1113
+ *
1114
+ * @param length the expected length
1115
+ */
1116
+ toHaveLength(length: number): void;
1117
+ /**
1118
+ * Asserts that a value has a property with the
1119
+ * expected name, and value if provided.
1120
+ *
1121
+ * @example
1122
+ * expect(new Set()).toHaveProperty("size");
1123
+ * expect(new Uint8Array()).toHaveProperty("byteLength", 0);
1124
+ * expect({ kitchen: { area: 20 }}).toHaveProperty("kitchen.area", 20);
1125
+ * expect({ kitchen: { area: 20 }}).toHaveProperty(["kitchen", "area"], 20);
1126
+ *
1127
+ * @param keyPath the expected property name or path, or an index
1128
+ * @param value the expected property value, if provided
1129
+ */
1130
+ toHaveProperty(keyPath: string | number | Array<string | number>, value?: unknown): void;
1131
+ /**
1132
+ * Asserts that a value is "truthy".
1133
+ *
1134
+ * To assert that a value equals `true`, use `toBe(true)` instead.
1135
+ *
1136
+ * @link https://developer.mozilla.org/en-US/docs/Glossary/Truthy
1137
+ * @example
1138
+ * expect(true).toBeTruthy();
1139
+ * expect(1).toBeTruthy();
1140
+ * expect({}).toBeTruthy();
1141
+ */
1142
+ toBeTruthy(): void;
1143
+ /**
1144
+ * Asserts that a value is "falsy".
1145
+ *
1146
+ * To assert that a value equals `false`, use `toBe(false)` instead.
1147
+ *
1148
+ * @link https://developer.mozilla.org/en-US/docs/Glossary/Falsy
1149
+ * @example
1150
+ * expect(true).toBeTruthy();
1151
+ * expect(1).toBeTruthy();
1152
+ * expect({}).toBeTruthy();
1153
+ */
1154
+ toBeFalsy(): void;
1155
+ /**
1156
+ * Asserts that a value is defined. (e.g. is not `undefined`)
1157
+ *
1158
+ * @example
1159
+ * expect(true).toBeDefined();
1160
+ * expect(undefined).toBeDefined(); // fail
1161
+ */
1162
+ toBeDefined(): void;
1163
+ /**
1164
+ * Asserts that the expected value is an instance of value
1165
+ *
1166
+ * @example
1167
+ * expect([]).toBeInstanceOf(Array);
1168
+ * expect(null).toBeInstanceOf(Array); // fail
1169
+ */
1170
+ toBeInstanceOf(value: unknown): void;
1171
+ /**
1172
+ * Asserts that the expected value is an instance of value
1173
+ *
1174
+ * @example
1175
+ * expect([]).toBeInstanceOf(Array);
1176
+ * expect(null).toBeInstanceOf(Array); // fail
1177
+ */
1178
+ toBeInstanceOf(value: unknown): void;
1179
+ /**
1180
+ * Asserts that a value is `undefined`.
1181
+ *
1182
+ * @example
1183
+ * expect(undefined).toBeUndefined();
1184
+ * expect(null).toBeUndefined(); // fail
1185
+ */
1186
+ toBeUndefined(): void;
1187
+ /**
1188
+ * Asserts that a value is `null`.
1189
+ *
1190
+ * @example
1191
+ * expect(null).toBeNull();
1192
+ * expect(undefined).toBeNull(); // fail
1193
+ */
1194
+ toBeNull(): void;
1195
+ /**
1196
+ * Asserts that a value is `NaN`.
1197
+ *
1198
+ * Same as using `Number.isNaN()`.
1199
+ *
1200
+ * @example
1201
+ * expect(NaN).toBeNaN();
1202
+ * expect(Infinity).toBeNaN(); // fail
1203
+ * expect("notanumber").toBeNaN(); // fail
1204
+ */
1205
+ toBeNaN(): void;
1206
+ /**
1207
+ * Asserts that a value is a `number` and is greater than the expected value.
1208
+ *
1209
+ * @example
1210
+ * expect(1).toBeGreaterThan(0);
1211
+ * expect(3.14).toBeGreaterThan(3);
1212
+ * expect(9).toBeGreaterThan(9); // fail
1213
+ *
1214
+ * @param expected the expected number
1215
+ */
1216
+ toBeGreaterThan(expected: number | bigint): void;
1217
+ /**
1218
+ * Asserts that a value is a `number` and is greater than or equal to the expected value.
1219
+ *
1220
+ * @example
1221
+ * expect(1).toBeGreaterThanOrEqual(0);
1222
+ * expect(3.14).toBeGreaterThanOrEqual(3);
1223
+ * expect(9).toBeGreaterThanOrEqual(9);
1224
+ *
1225
+ * @param expected the expected number
1226
+ */
1227
+ toBeGreaterThanOrEqual(expected: number | bigint): void;
1228
+ /**
1229
+ * Asserts that a value is a `number` and is less than the expected value.
1230
+ *
1231
+ * @example
1232
+ * expect(-1).toBeLessThan(0);
1233
+ * expect(3).toBeLessThan(3.14);
1234
+ * expect(9).toBeLessThan(9); // fail
1235
+ *
1236
+ * @param expected the expected number
1237
+ */
1238
+ toBeLessThan(expected: number | bigint): void;
1239
+ /**
1240
+ * Asserts that a value is a `number` and is less than or equal to the expected value.
1241
+ *
1242
+ * @example
1243
+ * expect(-1).toBeLessThanOrEqual(0);
1244
+ * expect(3).toBeLessThanOrEqual(3.14);
1245
+ * expect(9).toBeLessThanOrEqual(9);
1246
+ *
1247
+ * @param expected the expected number
1248
+ */
1249
+ toBeLessThanOrEqual(expected: number | bigint): void;
1250
+ /**
1251
+ * Asserts that a function throws an error.
1252
+ *
1253
+ * - If expected is a `string` or `RegExp`, it will check the `message` property.
1254
+ * - If expected is an `Error` object, it will check the `name` and `message` properties.
1255
+ * - If expected is an `Error` constructor, it will check the class of the `Error`.
1256
+ * - If expected is not provided, it will check if anything has thrown.
1257
+ *
1258
+ * @example
1259
+ * function fail() {
1260
+ * throw new Error("Oops!");
1261
+ * }
1262
+ * expect(fail).toThrow("Oops!");
1263
+ * expect(fail).toThrow(/oops/i);
1264
+ * expect(fail).toThrow(Error);
1265
+ * expect(fail).toThrow();
1266
+ *
1267
+ * @param expected the expected error, error message, or error pattern
1268
+ */
1269
+ toThrow(expected?: unknown): void;
1270
+ /**
1271
+ * Asserts that a function throws an error.
1272
+ *
1273
+ * - If expected is a `string` or `RegExp`, it will check the `message` property.
1274
+ * - If expected is an `Error` object, it will check the `name` and `message` properties.
1275
+ * - If expected is an `Error` constructor, it will check the class of the `Error`.
1276
+ * - If expected is not provided, it will check if anything has thrown.
1277
+ *
1278
+ * @example
1279
+ * function fail() {
1280
+ * throw new Error("Oops!");
1281
+ * }
1282
+ * expect(fail).toThrowError("Oops!");
1283
+ * expect(fail).toThrowError(/oops/i);
1284
+ * expect(fail).toThrowError(Error);
1285
+ * expect(fail).toThrowError();
1286
+ *
1287
+ * @param expected the expected error, error message, or error pattern
1288
+ * @alias toThrow
1289
+ */
1290
+ toThrowError(expected?: unknown): void;
1291
+ /**
1292
+ * Asserts that a value matches a regular expression or includes a substring.
1293
+ *
1294
+ * @example
1295
+ * expect("dog").toMatch(/dog/);
1296
+ * expect("dog").toMatch("og");
1297
+ *
1298
+ * @param expected the expected substring or pattern.
1299
+ */
1300
+ toMatch(expected: string | RegExp): void;
1301
+ /**
1302
+ * Asserts that a value matches the most recent snapshot.
1303
+ *
1304
+ * @example
1305
+ * expect([1, 2, 3]).toMatchSnapshot('hint message');
1306
+ * @param hint Hint used to identify the snapshot in the snapshot file.
1307
+ */
1308
+ toMatchSnapshot(hint?: string): void;
1309
+ /**
1310
+ * Asserts that a value matches the most recent snapshot.
1311
+ *
1312
+ * @example
1313
+ * expect([1, 2, 3]).toMatchSnapshot();
1314
+ * expect({ a: 1, b: 2 }).toMatchSnapshot({ a: 1 });
1315
+ * expect({ c: new Date() }).toMatchSnapshot({ c: expect.any(Date) });
1316
+ *
1317
+ * @param propertyMatchers Object containing properties to match against the value.
1318
+ * @param hint Hint used to identify the snapshot in the snapshot file.
1319
+ */
1320
+ toMatchSnapshot(propertyMatchers?: object, hint?: string): void;
1321
+ /**
1322
+ * Asserts that a value matches the most recent inline snapshot.
1323
+ *
1324
+ * @example
1325
+ * expect("Hello").toMatchInlineSnapshot();
1326
+ * expect("Hello").toMatchInlineSnapshot(`"Hello"`);
1327
+ *
1328
+ * @param value The latest automatically-updated snapshot value.
1329
+ */
1330
+ toMatchInlineSnapshot(value?: string): void;
1331
+ /**
1332
+ * Asserts that a value matches the most recent inline snapshot.
1333
+ *
1334
+ * @example
1335
+ * expect({ c: new Date() }).toMatchInlineSnapshot({ c: expect.any(Date) });
1336
+ * expect({ c: new Date() }).toMatchInlineSnapshot({ c: expect.any(Date) }, `
1337
+ * {
1338
+ * "v": Any<Date>,
1339
+ * }
1340
+ * `);
1341
+ *
1342
+ * @param propertyMatchers Object containing properties to match against the value.
1343
+ * @param value The latest automatically-updated snapshot value.
1344
+ */
1345
+ toMatchInlineSnapshot(propertyMatchers?: object, value?: string): void;
1346
+ /**
1347
+ * Asserts that a function throws an error matching the most recent snapshot.
1348
+ *
1349
+ * @example
1350
+ * function fail() {
1351
+ * throw new Error("Oops!");
1352
+ * }
1353
+ * expect(fail).toThrowErrorMatchingSnapshot();
1354
+ * expect(fail).toThrowErrorMatchingSnapshot("This one should say Oops!");
1355
+ *
1356
+ * @param value The latest automatically-updated snapshot value.
1357
+ */
1358
+ toThrowErrorMatchingSnapshot(hint?: string): void;
1359
+ /**
1360
+ * Asserts that a function throws an error matching the most recent snapshot.
1361
+ *
1362
+ * @example
1363
+ * function fail() {
1364
+ * throw new Error("Oops!");
1365
+ * }
1366
+ * expect(fail).toThrowErrorMatchingInlineSnapshot();
1367
+ * expect(fail).toThrowErrorMatchingInlineSnapshot(`"Oops!"`);
1368
+ *
1369
+ * @param value The latest automatically-updated snapshot value.
1370
+ */
1371
+ toThrowErrorMatchingInlineSnapshot(value?: string): void;
1372
+ /**
1373
+ * Asserts that an object matches a subset of properties.
1374
+ *
1375
+ * @example
1376
+ * expect({ a: 1, b: 2 }).toMatchObject({ b: 2 });
1377
+ * expect({ c: new Date(), d: 2 }).toMatchObject({ d: 2 });
1378
+ *
1379
+ * @param subset Subset of properties to match with.
1380
+ */
1381
+ toMatchObject(subset: object): void;
1382
+ /**
1383
+ * Asserts that a value is empty.
1384
+ *
1385
+ * @example
1386
+ * expect("").toBeEmpty();
1387
+ * expect([]).toBeEmpty();
1388
+ * expect({}).toBeEmpty();
1389
+ * expect(new Set()).toBeEmpty();
1390
+ */
1391
+ toBeEmpty(): void;
1392
+ /**
1393
+ * Asserts that a value is an empty `object`.
1394
+ *
1395
+ * @example
1396
+ * expect({}).toBeEmptyObject();
1397
+ * expect({ a: 'hello' }).not.toBeEmptyObject();
1398
+ */
1399
+ toBeEmptyObject(): void;
1400
+ /**
1401
+ * Asserts that a value is `null` or `undefined`.
1402
+ *
1403
+ * @example
1404
+ * expect(null).toBeNil();
1405
+ * expect(undefined).toBeNil();
1406
+ */
1407
+ toBeNil(): void;
1408
+ /**
1409
+ * Asserts that a value is a `array`.
1410
+ *
1411
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/array/#tobearray
1412
+ * @example
1413
+ * expect([1]).toBeArray();
1414
+ * expect(new Array(1)).toBeArray();
1415
+ * expect({}).not.toBeArray();
1416
+ */
1417
+ toBeArray(): void;
1418
+ /**
1419
+ * Asserts that a value is a `array` of a certain length.
1420
+ *
1421
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/array/#tobearrayofsize
1422
+ * @example
1423
+ * expect([]).toBeArrayOfSize(0);
1424
+ * expect([1]).toBeArrayOfSize(1);
1425
+ * expect(new Array(1)).toBeArrayOfSize(1);
1426
+ * expect({}).not.toBeArrayOfSize(0);
1427
+ */
1428
+ toBeArrayOfSize(size: number): void;
1429
+ /**
1430
+ * Asserts that a value is a `boolean`.
1431
+ *
1432
+ * @example
1433
+ * expect(true).toBeBoolean();
1434
+ * expect(false).toBeBoolean();
1435
+ * expect(null).not.toBeBoolean();
1436
+ * expect(0).not.toBeBoolean();
1437
+ */
1438
+ toBeBoolean(): void;
1439
+ /**
1440
+ * Asserts that a value is `true`.
1441
+ *
1442
+ * @example
1443
+ * expect(true).toBeTrue();
1444
+ * expect(false).not.toBeTrue();
1445
+ * expect(1).not.toBeTrue();
1446
+ */
1447
+ toBeTrue(): void;
1448
+ /**
1449
+ * Asserts that a value matches a specific type.
1450
+ *
1451
+ * @link https://vitest.dev/api/expect.html#tobetypeof
1452
+ * @example
1453
+ * expect(1).toBeTypeOf("number");
1454
+ * expect("hello").toBeTypeOf("string");
1455
+ * expect([]).not.toBeTypeOf("boolean");
1456
+ */
1457
+ toBeTypeOf(type: "bigint" | "boolean" | "function" | "number" | "object" | "string" | "symbol" | "undefined"): void;
1458
+ /**
1459
+ * Asserts that a value is `false`.
1460
+ *
1461
+ * @example
1462
+ * expect(false).toBeFalse();
1463
+ * expect(true).not.toBeFalse();
1464
+ * expect(0).not.toBeFalse();
1465
+ */
1466
+ toBeFalse(): void;
1467
+ /**
1468
+ * Asserts that a value is a `number`.
1469
+ *
1470
+ * @example
1471
+ * expect(1).toBeNumber();
1472
+ * expect(3.14).toBeNumber();
1473
+ * expect(NaN).toBeNumber();
1474
+ * expect(BigInt(1)).not.toBeNumber();
1475
+ */
1476
+ toBeNumber(): void;
1477
+ /**
1478
+ * Asserts that a value is a `number`, and is an integer.
1479
+ *
1480
+ * @example
1481
+ * expect(1).toBeInteger();
1482
+ * expect(3.14).not.toBeInteger();
1483
+ * expect(NaN).not.toBeInteger();
1484
+ */
1485
+ toBeInteger(): void;
1486
+ /**
1487
+ * Asserts that a value is an `object`.
1488
+ *
1489
+ * @example
1490
+ * expect({}).toBeObject();
1491
+ * expect("notAnObject").not.toBeObject();
1492
+ * expect(NaN).not.toBeObject();
1493
+ */
1494
+ toBeObject(): void;
1495
+ /**
1496
+ * Asserts that a value is a `number`, and is not `NaN` or `Infinity`.
1497
+ *
1498
+ * @example
1499
+ * expect(1).toBeFinite();
1500
+ * expect(3.14).toBeFinite();
1501
+ * expect(NaN).not.toBeFinite();
1502
+ * expect(Infinity).not.toBeFinite();
1503
+ */
1504
+ toBeFinite(): void;
1505
+ /**
1506
+ * Asserts that a value is a positive `number`.
1507
+ *
1508
+ * @example
1509
+ * expect(1).toBePositive();
1510
+ * expect(-3.14).not.toBePositive();
1511
+ * expect(NaN).not.toBePositive();
1512
+ */
1513
+ toBePositive(): void;
1514
+ /**
1515
+ * Asserts that a value is a negative `number`.
1516
+ *
1517
+ * @example
1518
+ * expect(-3.14).toBeNegative();
1519
+ * expect(1).not.toBeNegative();
1520
+ * expect(NaN).not.toBeNegative();
1521
+ */
1522
+ toBeNegative(): void;
1523
+ /**
1524
+ * Asserts that a value is a number between a start and end value.
1525
+ *
1526
+ * @param start the start number (inclusive)
1527
+ * @param end the end number (exclusive)
1528
+ */
1529
+ toBeWithin(start: number, end: number): void;
1530
+ /**
1531
+ * Asserts that a value is equal to the expected string, ignoring any whitespace.
1532
+ *
1533
+ * @example
1534
+ * expect(" foo ").toEqualIgnoringWhitespace("foo");
1535
+ * expect("bar").toEqualIgnoringWhitespace(" bar ");
1536
+ *
1537
+ * @param expected the expected string
1538
+ */
1539
+ toEqualIgnoringWhitespace(expected: string): void;
1540
+ /**
1541
+ * Asserts that a value is a `symbol`.
1542
+ *
1543
+ * @example
1544
+ * expect(Symbol("foo")).toBeSymbol();
1545
+ * expect("foo").not.toBeSymbol();
1546
+ */
1547
+ toBeSymbol(): void;
1548
+ /**
1549
+ * Asserts that a value is a `function`.
1550
+ *
1551
+ * @example
1552
+ * expect(() => {}).toBeFunction();
1553
+ */
1554
+ toBeFunction(): void;
1555
+ /**
1556
+ * Asserts that a value is a `Date` object.
1557
+ *
1558
+ * To check if a date is valid, use `toBeValidDate()` instead.
1559
+ *
1560
+ * @example
1561
+ * expect(new Date()).toBeDate();
1562
+ * expect(new Date(null)).toBeDate();
1563
+ * expect("2020-03-01").not.toBeDate();
1564
+ */
1565
+ toBeDate(): void;
1566
+ /**
1567
+ * Asserts that a value is a valid `Date` object.
1568
+ *
1569
+ * @example
1570
+ * expect(new Date()).toBeValidDate();
1571
+ * expect(new Date(null)).not.toBeValidDate();
1572
+ * expect("2020-03-01").not.toBeValidDate();
1573
+ */
1574
+ toBeValidDate(): void;
1575
+ /**
1576
+ * Asserts that a value is a `string`.
1577
+ *
1578
+ * @example
1579
+ * expect("foo").toBeString();
1580
+ * expect(new String("bar")).toBeString();
1581
+ * expect(123).not.toBeString();
1582
+ */
1583
+ toBeString(): void;
1584
+ /**
1585
+ * Asserts that a value includes a `string`.
1586
+ *
1587
+ * For non-string values, use `toContain()` instead.
1588
+ *
1589
+ * @param expected the expected substring
1590
+ */
1591
+ toInclude(expected: string): void;
1592
+ /**
1593
+ * Asserts that a value includes a `string` {times} times.
1594
+ * @param expected the expected substring
1595
+ * @param times the number of times the substring should occur
1596
+ */
1597
+ toIncludeRepeated(expected: string, times: number): void;
1598
+ /**
1599
+ * Checks whether a value satisfies a custom condition.
1600
+ * @param {Function} predicate - The custom condition to be satisfied. It should be a function that takes a value as an argument (in this case the value from expect) and returns a boolean.
1601
+ * @example
1602
+ * expect(1).toSatisfy((val) => val > 0);
1603
+ * expect("foo").toSatisfy((val) => val === "foo");
1604
+ * expect("bar").not.toSatisfy((val) => val === "bun");
1605
+ * @link https://vitest.dev/api/expect.html#tosatisfy
1606
+ * @link https://jest-extended.jestcommunity.dev/docs/matchers/toSatisfy
1607
+ */
1608
+ toSatisfy(predicate: (value: T) => boolean): void;
1609
+ /**
1610
+ * Asserts that a value starts with a `string`.
1611
+ *
1612
+ * @param expected the string to start with
1613
+ */
1614
+ toStartWith(expected: string): void;
1615
+ /**
1616
+ * Asserts that a value ends with a `string`.
1617
+ *
1618
+ * @param expected the string to end with
1619
+ */
1620
+ toEndWith(expected: string): void;
1621
+ /**
1622
+ * Ensures that a mock function has returned successfully at least once.
1623
+ *
1624
+ * A promise that is unfulfilled will be considered a failure. If the
1625
+ * function threw an error, it will be considered a failure.
1626
+ */
1627
+ toHaveReturned(): void;
1628
+
1629
+ /**
1630
+ * Ensures that a mock function has returned successfully at `times` times.
1631
+ *
1632
+ * A promise that is unfulfilled will be considered a failure. If the
1633
+ * function threw an error, it will be considered a failure.
1634
+ */
1635
+ toHaveReturnedTimes(times: number): void;
1866
1636
 
1867
- declare module "test" {
1868
- export type * from "bun:test";
1637
+ /**
1638
+ * Ensures that a mock function is called.
1639
+ */
1640
+ toHaveBeenCalled(): void;
1641
+ /**
1642
+ * Ensures that a mock function is called an exact number of times.
1643
+ * @alias toHaveBeenCalled
1644
+ */
1645
+ toBeCalled(): void;
1646
+ /**
1647
+ * Ensures that a mock function is called an exact number of times.
1648
+ */
1649
+ toHaveBeenCalledTimes(expected: number): void;
1650
+ /**
1651
+ * Ensure that a mock function is called with specific arguments.
1652
+ * @alias toHaveBeenCalledTimes
1653
+ */
1654
+ toBeCalledTimes(expected: number): void;
1655
+ /**
1656
+ * Ensure that a mock function is called with specific arguments.
1657
+ */
1658
+ toHaveBeenCalledWith(...expected: unknown[]): void;
1659
+ /**
1660
+ * Ensure that a mock function is called with specific arguments.
1661
+ * @alias toHaveBeenCalledWith
1662
+ */
1663
+ toBeCalledWith(...expected: unknown[]): void;
1664
+ /**
1665
+ * Ensure that a mock function is called with specific arguments for the last call.
1666
+ */
1667
+ toHaveBeenLastCalledWith(...expected: unknown[]): void;
1668
+ /**
1669
+ * Ensure that a mock function is called with specific arguments for the nth call.
1670
+ * @alias toHaveBeenCalledWith
1671
+ */
1672
+ lastCalledWith(...expected: unknown[]): void;
1673
+ /**
1674
+ * Ensure that a mock function is called with specific arguments for the nth call.
1675
+ */
1676
+ toHaveBeenNthCalledWith(n: number, ...expected: unknown[]): void;
1677
+ /**
1678
+ * Ensure that a mock function is called with specific arguments for the nth call.
1679
+ * @alias toHaveBeenCalledWith
1680
+ */
1681
+ nthCalledWith(n: number, ...expected: unknown[]): void;
1682
+ }
1683
+
1684
+ /**
1685
+ * Object representing an asymmetric matcher obtained by an static call to expect like `expect.anything()`, `expect.stringContaining("...")`, etc.
1686
+ */
1687
+ // Defined as an alias of `any` so that it does not trigger any type mismatch
1688
+ export type AsymmetricMatcher = any;
1689
+
1690
+ export interface MatcherResult {
1691
+ pass: boolean;
1692
+ message?: string | (() => string);
1693
+ }
1694
+
1695
+ export type CustomMatcher<E, P extends any[]> = (
1696
+ this: MatcherContext,
1697
+ expected: E,
1698
+ ...matcherArguments: P
1699
+ ) => MatcherResult | Promise<MatcherResult>;
1700
+
1701
+ /** All non-builtin matchers and asymmetric matchers that have been type-registered through declaration merging */
1702
+ export type CustomMatchersDetected = Omit<Matchers<unknown>, keyof MatchersBuiltin<unknown>> &
1703
+ Omit<AsymmetricMatchers, keyof AsymmetricMatchersBuiltin>;
1704
+
1705
+ /**
1706
+ * If the types has been defined through declaration merging, enforce it.
1707
+ * Otherwise enforce the generic custom matcher signature.
1708
+ */
1709
+ export type ExpectExtendMatchers<M> = {
1710
+ [k in keyof M]: k extends keyof CustomMatchersDetected
1711
+ ? CustomMatcher<unknown, Parameters<CustomMatchersDetected[k]>>
1712
+ : CustomMatcher<unknown, any[]>;
1713
+ };
1714
+
1715
+ /** Custom equality tester */
1716
+ export type Tester = (this: TesterContext, a: any, b: any, customTesters: Tester[]) => boolean | undefined;
1717
+
1718
+ export type EqualsFunction = (
1719
+ a: unknown,
1720
+ b: unknown,
1721
+ //customTesters?: Array<Tester>,
1722
+ //strictCheck?: boolean,
1723
+ ) => boolean;
1724
+
1725
+ export interface TesterContext {
1726
+ equals: EqualsFunction;
1727
+ }
1728
+
1729
+ interface MatcherState {
1730
+ //assertionCalls: number;
1731
+ //currentConcurrentTestName?: () => string | undefined;
1732
+ //currentTestName?: string;
1733
+ //error?: Error;
1734
+ //expand: boolean;
1735
+ //expectedAssertionsNumber: number | null;
1736
+ //expectedAssertionsNumberError?: Error;
1737
+ //isExpectingAssertions: boolean;
1738
+ //isExpectingAssertionsError?: Error;
1739
+ isNot: boolean;
1740
+ //numPassingAsserts: number;
1741
+ promise: string;
1742
+ //suppressedErrors: Array<Error>;
1743
+ //testPath?: string;
1744
+ }
1745
+
1746
+ type MatcherHintColor = (arg: string) => string; // subset of Chalk type
1747
+
1748
+ interface MatcherUtils {
1749
+ //customTesters: Array<Tester>;
1750
+ //dontThrow(): void; // (internally used by jest snapshot)
1751
+ equals: EqualsFunction;
1752
+ utils: Readonly<{
1753
+ stringify(value: unknown): string;
1754
+ printReceived(value: unknown): string;
1755
+ printExpected(value: unknown): string;
1756
+ matcherHint(
1757
+ matcherName: string,
1758
+ received?: unknown,
1759
+ expected?: unknown,
1760
+ options?: {
1761
+ isNot?: boolean;
1762
+ promise?: string;
1763
+ isDirectExpectCall?: boolean; // (internal)
1764
+ comment?: string;
1765
+ expectedColor?: MatcherHintColor;
1766
+ receivedColor?: MatcherHintColor;
1767
+ secondArgument?: string;
1768
+ secondArgumentColor?: MatcherHintColor;
1769
+ },
1770
+ ): string;
1771
+ //iterableEquality: Tester;
1772
+ //subsetEquality: Tester;
1773
+ // ...
1774
+ }>;
1775
+ }
1776
+
1777
+ type MatcherContext = MatcherUtils & MatcherState;
1869
1778
  }
1870
1779
 
1871
1780
  declare namespace JestMock {
1872
- /**
1873
- * Copyright (c) Meta Platforms, Inc. and affiliates.
1874
- *
1875
- * This source code is licensed under the MIT license found in the
1876
- * LICENSE file in the root directory of this source tree.
1877
- */
1878
- export interface ClassLike {
1879
- new (...args: any): any;
1880
- }
1881
-
1882
- export type ConstructorLikeKeys<T> = keyof {
1883
- [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K];
1884
- };
1885
-
1886
- // export const fn: <T extends FunctionLike = UnknownFunction>(
1887
- // implementation?: T | undefined,
1888
- // ) => Mock<T>;
1889
-
1890
- export type FunctionLike = (...args: any) => any;
1891
-
1892
- export type MethodLikeKeys<T> = keyof {
1893
- [K in keyof T as Required<T>[K] extends FunctionLike ? K : never]: T[K];
1894
- };
1895
-
1896
- export interface Mock<T extends (...args: any[]) => any>
1897
- extends MockInstance<T> {
1898
- (...args: Parameters<T>): ReturnType<T>;
1899
- }
1900
-
1901
- /**
1902
- * All what the internal typings need is to be sure that we have any-function.
1903
- * `FunctionLike` type ensures that and helps to constrain the type as well.
1904
- * The default of `UnknownFunction` makes sure that `any`s do not leak to the
1905
- * user side. For instance, calling `fn()` without implementation will return
1906
- * a mock of `(...args: Array<unknown>) => unknown` type. If implementation
1907
- * is provided, its typings are inferred correctly.
1908
- */
1909
- // export interface Mock<T extends FunctionLike = UnknownFunction>
1910
- // extends Function,
1911
- // MockInstance<T> {
1912
- // new (...args: Parameters<T>): ReturnType<T>;
1913
- // (...args: Parameters<T>): ReturnType<T>;
1914
- // }
1915
-
1916
- // export type Mocked<T> = T extends ClassLike
1917
- // ? MockedClass<T>
1918
- // : T extends FunctionLike
1919
- // ? MockedFunction<T>
1920
- // : T extends object
1921
- // ? MockedObject<T>
1922
- // : T;
1923
-
1924
- // export const mocked: {
1925
- // <T extends object>(
1926
- // source: T,
1927
- // options?: {
1928
- // shallow: false;
1929
- // },
1930
- // ): Mocked<T>;
1931
- // <T_1 extends object>(
1932
- // source: T_1,
1933
- // options: {
1934
- // shallow: true;
1935
- // },
1936
- // ): MockedShallow<T_1>;
1937
- // };
1938
-
1939
- // export type MockedClass<T extends ClassLike> = MockInstance<
1940
- // (...args: ConstructorParameters<T>) => Mocked<InstanceType<T>>
1941
- // > &
1942
- // MockedObject<T>;
1943
-
1944
- // export type MockedFunction<T extends FunctionLike> = MockInstance<T> &
1945
- // MockedObject<T>;
1946
-
1947
- // type MockedFunctionShallow<T extends FunctionLike> = MockInstance<T> & T;
1948
-
1949
- // export type MockedObject<T extends object> = {
1950
- // [K in keyof T]: T[K] extends ClassLike
1951
- // ? MockedClass<T[K]>
1952
- // : T[K] extends FunctionLike
1953
- // ? MockedFunction<T[K]>
1954
- // : T[K] extends object
1955
- // ? MockedObject<T[K]>
1956
- // : T[K];
1957
- // } & T;
1958
-
1959
- // type MockedObjectShallow<T extends object> = {
1960
- // [K in keyof T]: T[K] extends ClassLike
1961
- // ? MockedClass<T[K]>
1962
- // : T[K] extends FunctionLike
1963
- // ? MockedFunctionShallow<T[K]>
1964
- // : T[K];
1965
- // } & T;
1966
-
1967
- // export type MockedShallow<T> = T extends ClassLike
1968
- // ? MockedClass<T>
1969
- // : T extends FunctionLike
1970
- // ? MockedFunctionShallow<T>
1971
- // : T extends object
1972
- // ? MockedObjectShallow<T>
1973
- // : T;
1974
-
1975
- // export type MockFunctionMetadata<
1976
- // T = unknown,
1977
- // MetadataType = MockMetadataType,
1978
- // > = MockMetadata<T, MetadataType>;
1979
-
1980
- // export type MockFunctionMetadataType = MockMetadataType;
1981
-
1982
- type MockFunctionResult<T extends FunctionLike = UnknownFunction> =
1983
- | MockFunctionResultIncomplete
1984
- | MockFunctionResultReturn<T>
1985
- | MockFunctionResultThrow;
1986
-
1987
- interface MockFunctionResultIncomplete {
1988
- type: "incomplete";
1989
- /**
1990
- * Result of a single call to a mock function that has not yet completed.
1991
- * This occurs if you test the result from within the mock function itself,
1992
- * or from within a function that was called by the mock.
1993
- */
1994
- value: undefined;
1995
- }
1996
-
1997
- interface MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> {
1998
- type: "return";
1999
- /**
2000
- * Result of a single call to a mock function that returned.
2001
- */
2002
- value: ReturnType<T>;
2003
- }
2004
-
2005
- interface MockFunctionResultThrow {
2006
- type: "throw";
2007
- /**
2008
- * Result of a single call to a mock function that threw.
2009
- */
2010
- value: unknown;
2011
- }
2012
-
2013
- interface MockFunctionState<T extends FunctionLike = FunctionLike> {
2014
- /**
2015
- * List of the call arguments of all calls that have been made to the mock.
2016
- */
2017
- calls: Array<Parameters<T>>;
2018
- /**
2019
- * List of all the object instances that have been instantiated from the mock.
2020
- */
2021
- instances: Array<ReturnType<T>>;
2022
- /**
2023
- * List of all the function contexts that have been applied to calls to the mock.
2024
- */
2025
- contexts: Array<ThisParameterType<T>>;
2026
- /**
2027
- * List of the call order indexes of the mock. Jest is indexing the order of
2028
- * invocations of all mocks in a test file. The index is starting with `1`.
2029
- */
2030
- invocationCallOrder: number[];
2031
- /**
2032
- * List of the call arguments of the last call that was made to the mock.
2033
- * If the function was not called, it will return `undefined`.
2034
- */
2035
- lastCall?: Parameters<T>;
2036
- /**
2037
- * List of the results of all calls that have been made to the mock.
2038
- */
2039
- results: Array<MockFunctionResult<T>>;
2040
- }
2041
-
2042
- export interface MockInstance<T extends FunctionLike = UnknownFunction> {
2043
- _isMockFunction: true;
2044
- _protoImpl: Function;
2045
- getMockImplementation(): T | undefined;
2046
- getMockName(): string;
2047
- mock: MockFunctionState<T>;
2048
- mockClear(): this;
2049
- mockReset(): this;
2050
- mockRestore(): void;
2051
- mockImplementation(fn: T): this;
2052
- mockImplementationOnce(fn: T): this;
2053
- withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
2054
- withImplementation(fn: T, callback: () => void): void;
2055
- mockName(name: string): this;
2056
- mockReturnThis(): this;
2057
- mockReturnValue(value: ReturnType<T>): this;
2058
- mockReturnValueOnce(value: ReturnType<T>): this;
2059
- mockResolvedValue(value: ResolveType<T>): this;
2060
- mockResolvedValueOnce(value: ResolveType<T>): this;
2061
- mockRejectedValue(value: RejectType<T>): this;
2062
- mockRejectedValueOnce(value: RejectType<T>): this;
2063
- }
2064
-
2065
- // export type MockMetadata<T, MetadataType = MockMetadataType> = {
2066
- // ref?: number;
2067
- // members?: Record<string, MockMetadata<T>>;
2068
- // mockImpl?: T;
2069
- // name?: string;
2070
- // refID?: number;
2071
- // type?: MetadataType;
2072
- // value?: T;
2073
- // length?: number;
2074
- // };
2075
-
2076
- // export type MockMetadataType =
2077
- // | "object"
2078
- // | "array"
2079
- // | "regexp"
2080
- // | "function"
2081
- // | "constant"
2082
- // | "collection"
2083
- // | "null"
2084
- // | "undefined";
2085
-
2086
- // export class ModuleMocker {
2087
- // private readonly _environmentGlobal;
2088
- // private _mockState;
2089
- // private _mockConfigRegistry;
2090
- // private _spyState;
2091
- // private _invocationCallCounter;
2092
- // /**
2093
- // * @see README.md
2094
- // * @param global Global object of the test environment, used to create
2095
- // * mocks
2096
- // */
2097
- // constructor(global: typeof globalThis);
2098
- // private _getSlots;
2099
- // private _ensureMockConfig;
2100
- // private _ensureMockState;
2101
- // private _defaultMockConfig;
2102
- // private _defaultMockState;
2103
- // private _makeComponent;
2104
- // private _createMockFunction;
2105
- // private _generateMock;
2106
- // /**
2107
- // * Check whether the given property of an object has been already replaced.
2108
- // */
2109
- // private _findReplacedProperty;
2110
- // /**
2111
- // * @see README.md
2112
- // * @param metadata Metadata for the mock in the schema returned by the
2113
- // * getMetadata method of this module.
2114
- // */
2115
- // generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T>;
2116
- // /**
2117
- // * @see README.md
2118
- // * @param component The component for which to retrieve metadata.
2119
- // */
2120
- // getMetadata<T = unknown>(
2121
- // component: T,
2122
- // _refs?: Map<T, number>,
2123
- // ): MockMetadata<T> | null;
2124
- // isMockFunction<T extends FunctionLike = UnknownFunction>(
2125
- // fn: MockInstance<T>,
2126
- // ): fn is MockInstance<T>;
2127
- // isMockFunction<P extends Array<unknown>, R>(
2128
- // fn: (...args: P) => R,
2129
- // ): fn is Mock<(...args: P) => R>;
2130
- // isMockFunction(fn: unknown): fn is Mock<UnknownFunction>;
2131
- // fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
2132
- // private _attachMockImplementation;
2133
- // spyOn<
2134
- // T extends object,
2135
- // K extends PropertyLikeKeys<T>,
2136
- // A extends "get" | "set",
2137
- // >(
2138
- // object: T,
2139
- // methodKey: K,
2140
- // accessType: A,
2141
- // ): A extends "get"
2142
- // ? SpiedGetter<T[K]>
2143
- // : A extends "set"
2144
- // ? SpiedSetter<T[K]>
2145
- // : never;
2146
- // spyOn<
2147
- // T extends object,
2148
- // K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>,
2149
- // V extends Required<T>[K],
2150
- // >(
2151
- // object: T,
2152
- // methodKey: K,
2153
- // ): V extends ClassLike | FunctionLike ? Spied<V> : never;
2154
- // private _spyOnProperty;
2155
- // replaceProperty<
2156
- // T extends object,
2157
- // K extends PropertyLikeKeys<T>,
2158
- // V extends T[K],
2159
- // >(object: T, propertyKey: K, value: V): Replaced<T[K]>;
2160
- // clearAllMocks(): void;
2161
- // resetAllMocks(): void;
2162
- // restoreAllMocks(): void;
2163
- // private _typeOf;
2164
- // mocked<T extends object>(
2165
- // source: T,
2166
- // options?: {
2167
- // shallow: false;
2168
- // },
2169
- // ): Mocked<T>;
2170
- // mocked<T extends object>(
2171
- // source: T,
2172
- // options: {
2173
- // shallow: true;
2174
- // },
2175
- // ): MockedShallow<T>;
2176
- // }
2177
-
2178
- export type PropertyLikeKeys<T> = Exclude<
2179
- keyof T,
2180
- ConstructorLikeKeys<T> | MethodLikeKeys<T>
2181
- >;
2182
-
2183
- export type RejectType<T extends FunctionLike> =
2184
- ReturnType<T> extends PromiseLike<any> ? unknown : never;
2185
-
2186
- export interface Replaced<T = unknown> {
2187
- /**
2188
- * Restore property to its original value known at the time of mocking.
2189
- */
2190
- restore(): void;
2191
- /**
2192
- * Change the value of the property.
2193
- */
2194
- replaceValue(value: T): this;
2195
- }
2196
-
2197
- export function replaceProperty<
2198
- T extends object,
2199
- K_2 extends Exclude<
2200
- keyof T,
2201
- | keyof {
2202
- [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K];
2203
- }
2204
- | keyof {
2205
- [K_1 in keyof T as Required<T>[K_1] extends FunctionLike
2206
- ? K_1
2207
- : never]: T[K_1];
2208
- }
2209
- >,
2210
- V extends T[K_2],
2211
- >(object: T, propertyKey: K_2, value: V): Replaced<T[K_2]>;
2212
-
2213
- export type ResolveType<T extends FunctionLike> =
2214
- ReturnType<T> extends PromiseLike<infer U> ? U : never;
2215
-
2216
- export type Spied<T extends ClassLike | FunctionLike> = T extends ClassLike
2217
- ? SpiedClass<T>
2218
- : T extends FunctionLike
2219
- ? SpiedFunction<T>
2220
- : never;
2221
-
2222
- export type SpiedClass<T extends ClassLike = UnknownClass> = MockInstance<
2223
- (...args: ConstructorParameters<T>) => InstanceType<T>
2224
- >;
2225
-
2226
- export type SpiedFunction<T extends FunctionLike = UnknownFunction> =
2227
- MockInstance<(...args: Parameters<T>) => ReturnType<T>>;
2228
-
2229
- export type SpiedGetter<T> = MockInstance<() => T>;
2230
-
2231
- export type SpiedSetter<T> = MockInstance<(arg: T) => void>;
2232
-
2233
- export interface SpyInstance<T extends FunctionLike = UnknownFunction>
2234
- extends MockInstance<T> {}
2235
-
2236
- export const spyOn: {
2237
- <
2238
- T extends object,
2239
- K_2 extends Exclude<
2240
- keyof T,
2241
- | keyof {
2242
- [K in keyof T as Required<T>[K] extends ClassLike
2243
- ? K
2244
- : never]: T[K];
2245
- }
2246
- | keyof {
2247
- [K_1 in keyof T as Required<T>[K_1] extends FunctionLike
2248
- ? K_1
2249
- : never]: T[K_1];
2250
- }
2251
- >,
2252
- V extends Required<T>[K_2],
2253
- A extends "set" | "get",
2254
- >(
2255
- object: T,
2256
- methodKey: K_2,
2257
- accessType: A,
2258
- ): A extends "get"
2259
- ? SpiedGetter<V>
2260
- : A extends "set"
2261
- ? SpiedSetter<V>
2262
- : never;
2263
- <
2264
- T_1 extends object,
2265
- K_5 extends
2266
- | keyof {
2267
- [K_3 in keyof T_1 as Required<T_1>[K_3] extends ClassLike
2268
- ? K_3
2269
- : never]: T_1[K_3];
2270
- }
2271
- | keyof {
2272
- [K_4 in keyof T_1 as Required<T_1>[K_4] extends FunctionLike
2273
- ? K_4
2274
- : never]: T_1[K_4];
2275
- },
2276
- V_1 extends Required<T_1>[K_5],
2277
- >(
2278
- object: T_1,
2279
- methodKey: K_5,
2280
- ): V_1 extends ClassLike | FunctionLike ? Spied<V_1> : never;
2281
- };
2282
-
2283
- export interface UnknownClass {
2284
- new (...args: unknown[]): unknown;
2285
- }
2286
-
2287
- export type UnknownFunction = (...args: unknown[]) => unknown;
1781
+ /**
1782
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1783
+ *
1784
+ * This source code is licensed under the MIT license found in the
1785
+ * LICENSE file in the root directory of this source tree.
1786
+ */
1787
+ export interface ClassLike {
1788
+ new (...args: any): any;
1789
+ }
1790
+
1791
+ export type ConstructorLikeKeys<T> = keyof {
1792
+ [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K];
1793
+ };
1794
+
1795
+ // export const fn: <T extends FunctionLike = UnknownFunction>(
1796
+ // implementation?: T | undefined,
1797
+ // ) => Mock<T>;
1798
+
1799
+ export type FunctionLike = (...args: any) => any;
1800
+
1801
+ export type MethodLikeKeys<T> = keyof {
1802
+ [K in keyof T as Required<T>[K] extends FunctionLike ? K : never]: T[K];
1803
+ };
1804
+
1805
+ export interface Mock<T extends (...args: any[]) => any> extends MockInstance<T> {
1806
+ (...args: Parameters<T>): ReturnType<T>;
1807
+ }
1808
+
1809
+ /**
1810
+ * All what the internal typings need is to be sure that we have any-function.
1811
+ * `FunctionLike` type ensures that and helps to constrain the type as well.
1812
+ * The default of `UnknownFunction` makes sure that `any`s do not leak to the
1813
+ * user side. For instance, calling `fn()` without implementation will return
1814
+ * a mock of `(...args: Array<unknown>) => unknown` type. If implementation
1815
+ * is provided, its typings are inferred correctly.
1816
+ */
1817
+ // export interface Mock<T extends FunctionLike = UnknownFunction>
1818
+ // extends Function,
1819
+ // MockInstance<T> {
1820
+ // new (...args: Parameters<T>): ReturnType<T>;
1821
+ // (...args: Parameters<T>): ReturnType<T>;
1822
+ // }
1823
+
1824
+ // export type Mocked<T> = T extends ClassLike
1825
+ // ? MockedClass<T>
1826
+ // : T extends FunctionLike
1827
+ // ? MockedFunction<T>
1828
+ // : T extends object
1829
+ // ? MockedObject<T>
1830
+ // : T;
1831
+
1832
+ // export const mocked: {
1833
+ // <T extends object>(
1834
+ // source: T,
1835
+ // options?: {
1836
+ // shallow: false;
1837
+ // },
1838
+ // ): Mocked<T>;
1839
+ // <T_1 extends object>(
1840
+ // source: T_1,
1841
+ // options: {
1842
+ // shallow: true;
1843
+ // },
1844
+ // ): MockedShallow<T_1>;
1845
+ // };
1846
+
1847
+ // export type MockedClass<T extends ClassLike> = MockInstance<
1848
+ // (...args: ConstructorParameters<T>) => Mocked<InstanceType<T>>
1849
+ // > &
1850
+ // MockedObject<T>;
1851
+
1852
+ // export type MockedFunction<T extends FunctionLike> = MockInstance<T> &
1853
+ // MockedObject<T>;
1854
+
1855
+ // type MockedFunctionShallow<T extends FunctionLike> = MockInstance<T> & T;
1856
+
1857
+ // export type MockedObject<T extends object> = {
1858
+ // [K in keyof T]: T[K] extends ClassLike
1859
+ // ? MockedClass<T[K]>
1860
+ // : T[K] extends FunctionLike
1861
+ // ? MockedFunction<T[K]>
1862
+ // : T[K] extends object
1863
+ // ? MockedObject<T[K]>
1864
+ // : T[K];
1865
+ // } & T;
1866
+
1867
+ // type MockedObjectShallow<T extends object> = {
1868
+ // [K in keyof T]: T[K] extends ClassLike
1869
+ // ? MockedClass<T[K]>
1870
+ // : T[K] extends FunctionLike
1871
+ // ? MockedFunctionShallow<T[K]>
1872
+ // : T[K];
1873
+ // } & T;
1874
+
1875
+ // export type MockedShallow<T> = T extends ClassLike
1876
+ // ? MockedClass<T>
1877
+ // : T extends FunctionLike
1878
+ // ? MockedFunctionShallow<T>
1879
+ // : T extends object
1880
+ // ? MockedObjectShallow<T>
1881
+ // : T;
1882
+
1883
+ // export type MockFunctionMetadata<
1884
+ // T = unknown,
1885
+ // MetadataType = MockMetadataType,
1886
+ // > = MockMetadata<T, MetadataType>;
1887
+
1888
+ // export type MockFunctionMetadataType = MockMetadataType;
1889
+
1890
+ type MockFunctionResult<T extends FunctionLike = UnknownFunction> =
1891
+ | MockFunctionResultIncomplete
1892
+ | MockFunctionResultReturn<T>
1893
+ | MockFunctionResultThrow;
1894
+
1895
+ interface MockFunctionResultIncomplete {
1896
+ type: "incomplete";
1897
+ /**
1898
+ * Result of a single call to a mock function that has not yet completed.
1899
+ * This occurs if you test the result from within the mock function itself,
1900
+ * or from within a function that was called by the mock.
1901
+ */
1902
+ value: undefined;
1903
+ }
1904
+
1905
+ interface MockFunctionResultReturn<T extends FunctionLike = UnknownFunction> {
1906
+ type: "return";
1907
+ /**
1908
+ * Result of a single call to a mock function that returned.
1909
+ */
1910
+ value: ReturnType<T>;
1911
+ }
1912
+
1913
+ interface MockFunctionResultThrow {
1914
+ type: "throw";
1915
+ /**
1916
+ * Result of a single call to a mock function that threw.
1917
+ */
1918
+ value: unknown;
1919
+ }
1920
+
1921
+ interface MockFunctionState<T extends FunctionLike = FunctionLike> {
1922
+ /**
1923
+ * List of the call arguments of all calls that have been made to the mock.
1924
+ */
1925
+ calls: Array<Parameters<T>>;
1926
+ /**
1927
+ * List of all the object instances that have been instantiated from the mock.
1928
+ */
1929
+ instances: Array<ReturnType<T>>;
1930
+ /**
1931
+ * List of all the function contexts that have been applied to calls to the mock.
1932
+ */
1933
+ contexts: Array<ThisParameterType<T>>;
1934
+ /**
1935
+ * List of the call order indexes of the mock. Jest is indexing the order of
1936
+ * invocations of all mocks in a test file. The index is starting with `1`.
1937
+ */
1938
+ invocationCallOrder: number[];
1939
+ /**
1940
+ * List of the call arguments of the last call that was made to the mock.
1941
+ * If the function was not called, it will return `undefined`.
1942
+ */
1943
+ lastCall?: Parameters<T>;
1944
+ /**
1945
+ * List of the results of all calls that have been made to the mock.
1946
+ */
1947
+ results: Array<MockFunctionResult<T>>;
1948
+ }
1949
+
1950
+ export interface MockInstance<T extends FunctionLike = UnknownFunction> {
1951
+ _isMockFunction: true;
1952
+ _protoImpl: Function;
1953
+ getMockImplementation(): T | undefined;
1954
+ getMockName(): string;
1955
+ mock: MockFunctionState<T>;
1956
+ mockClear(): this;
1957
+ mockReset(): this;
1958
+ mockRestore(): void;
1959
+ mockImplementation(fn: T): this;
1960
+ mockImplementationOnce(fn: T): this;
1961
+ withImplementation(fn: T, callback: () => Promise<unknown>): Promise<void>;
1962
+ withImplementation(fn: T, callback: () => void): void;
1963
+ mockName(name: string): this;
1964
+ mockReturnThis(): this;
1965
+ mockReturnValue(value: ReturnType<T>): this;
1966
+ mockReturnValueOnce(value: ReturnType<T>): this;
1967
+ mockResolvedValue(value: ResolveType<T>): this;
1968
+ mockResolvedValueOnce(value: ResolveType<T>): this;
1969
+ mockRejectedValue(value: RejectType<T>): this;
1970
+ mockRejectedValueOnce(value: RejectType<T>): this;
1971
+ }
1972
+
1973
+ // export type MockMetadata<T, MetadataType = MockMetadataType> = {
1974
+ // ref?: number;
1975
+ // members?: Record<string, MockMetadata<T>>;
1976
+ // mockImpl?: T;
1977
+ // name?: string;
1978
+ // refID?: number;
1979
+ // type?: MetadataType;
1980
+ // value?: T;
1981
+ // length?: number;
1982
+ // };
1983
+
1984
+ // export type MockMetadataType =
1985
+ // | "object"
1986
+ // | "array"
1987
+ // | "regexp"
1988
+ // | "function"
1989
+ // | "constant"
1990
+ // | "collection"
1991
+ // | "null"
1992
+ // | "undefined";
1993
+
1994
+ // export class ModuleMocker {
1995
+ // private readonly _environmentGlobal;
1996
+ // private _mockState;
1997
+ // private _mockConfigRegistry;
1998
+ // private _spyState;
1999
+ // private _invocationCallCounter;
2000
+ // /**
2001
+ // * @see README.md
2002
+ // * @param global Global object of the test environment, used to create
2003
+ // * mocks
2004
+ // */
2005
+ // constructor(global: typeof globalThis);
2006
+ // private _getSlots;
2007
+ // private _ensureMockConfig;
2008
+ // private _ensureMockState;
2009
+ // private _defaultMockConfig;
2010
+ // private _defaultMockState;
2011
+ // private _makeComponent;
2012
+ // private _createMockFunction;
2013
+ // private _generateMock;
2014
+ // /**
2015
+ // * Check whether the given property of an object has been already replaced.
2016
+ // */
2017
+ // private _findReplacedProperty;
2018
+ // /**
2019
+ // * @see README.md
2020
+ // * @param metadata Metadata for the mock in the schema returned by the
2021
+ // * getMetadata method of this module.
2022
+ // */
2023
+ // generateFromMetadata<T>(metadata: MockMetadata<T>): Mocked<T>;
2024
+ // /**
2025
+ // * @see README.md
2026
+ // * @param component The component for which to retrieve metadata.
2027
+ // */
2028
+ // getMetadata<T = unknown>(
2029
+ // component: T,
2030
+ // _refs?: Map<T, number>,
2031
+ // ): MockMetadata<T> | null;
2032
+ // isMockFunction<T extends FunctionLike = UnknownFunction>(
2033
+ // fn: MockInstance<T>,
2034
+ // ): fn is MockInstance<T>;
2035
+ // isMockFunction<P extends Array<unknown>, R>(
2036
+ // fn: (...args: P) => R,
2037
+ // ): fn is Mock<(...args: P) => R>;
2038
+ // isMockFunction(fn: unknown): fn is Mock<UnknownFunction>;
2039
+ // fn<T extends FunctionLike = UnknownFunction>(implementation?: T): Mock<T>;
2040
+ // private _attachMockImplementation;
2041
+ // spyOn<
2042
+ // T extends object,
2043
+ // K extends PropertyLikeKeys<T>,
2044
+ // A extends "get" | "set",
2045
+ // >(
2046
+ // object: T,
2047
+ // methodKey: K,
2048
+ // accessType: A,
2049
+ // ): A extends "get"
2050
+ // ? SpiedGetter<T[K]>
2051
+ // : A extends "set"
2052
+ // ? SpiedSetter<T[K]>
2053
+ // : never;
2054
+ // spyOn<
2055
+ // T extends object,
2056
+ // K extends ConstructorLikeKeys<T> | MethodLikeKeys<T>,
2057
+ // V extends Required<T>[K],
2058
+ // >(
2059
+ // object: T,
2060
+ // methodKey: K,
2061
+ // ): V extends ClassLike | FunctionLike ? Spied<V> : never;
2062
+ // private _spyOnProperty;
2063
+ // replaceProperty<
2064
+ // T extends object,
2065
+ // K extends PropertyLikeKeys<T>,
2066
+ // V extends T[K],
2067
+ // >(object: T, propertyKey: K, value: V): Replaced<T[K]>;
2068
+ // clearAllMocks(): void;
2069
+ // resetAllMocks(): void;
2070
+ // restoreAllMocks(): void;
2071
+ // private _typeOf;
2072
+ // mocked<T extends object>(
2073
+ // source: T,
2074
+ // options?: {
2075
+ // shallow: false;
2076
+ // },
2077
+ // ): Mocked<T>;
2078
+ // mocked<T extends object>(
2079
+ // source: T,
2080
+ // options: {
2081
+ // shallow: true;
2082
+ // },
2083
+ // ): MockedShallow<T>;
2084
+ // }
2085
+
2086
+ export type PropertyLikeKeys<T> = Exclude<keyof T, ConstructorLikeKeys<T> | MethodLikeKeys<T>>;
2087
+
2088
+ export type RejectType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<any> ? unknown : never;
2089
+
2090
+ export interface Replaced<T = unknown> {
2091
+ /**
2092
+ * Restore property to its original value known at the time of mocking.
2093
+ */
2094
+ restore(): void;
2095
+ /**
2096
+ * Change the value of the property.
2097
+ */
2098
+ replaceValue(value: T): this;
2099
+ }
2100
+
2101
+ export function replaceProperty<
2102
+ T extends object,
2103
+ K_2 extends Exclude<
2104
+ keyof T,
2105
+ | keyof {
2106
+ [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K];
2107
+ }
2108
+ | keyof {
2109
+ [K_1 in keyof T as Required<T>[K_1] extends FunctionLike ? K_1 : never]: T[K_1];
2110
+ }
2111
+ >,
2112
+ V extends T[K_2],
2113
+ >(object: T, propertyKey: K_2, value: V): Replaced<T[K_2]>;
2114
+
2115
+ export type ResolveType<T extends FunctionLike> = ReturnType<T> extends PromiseLike<infer U> ? U : never;
2116
+
2117
+ export type Spied<T extends ClassLike | FunctionLike> = T extends ClassLike
2118
+ ? SpiedClass<T>
2119
+ : T extends FunctionLike
2120
+ ? SpiedFunction<T>
2121
+ : never;
2122
+
2123
+ export type SpiedClass<T extends ClassLike = UnknownClass> = MockInstance<
2124
+ (...args: ConstructorParameters<T>) => InstanceType<T>
2125
+ >;
2126
+
2127
+ export type SpiedFunction<T extends FunctionLike = UnknownFunction> = MockInstance<
2128
+ (...args: Parameters<T>) => ReturnType<T>
2129
+ >;
2130
+
2131
+ export type SpiedGetter<T> = MockInstance<() => T>;
2132
+
2133
+ export type SpiedSetter<T> = MockInstance<(arg: T) => void>;
2134
+
2135
+ export interface SpyInstance<T extends FunctionLike = UnknownFunction> extends MockInstance<T> {}
2136
+
2137
+ export const spyOn: {
2138
+ <
2139
+ T extends object,
2140
+ K_2 extends Exclude<
2141
+ keyof T,
2142
+ | keyof {
2143
+ [K in keyof T as Required<T>[K] extends ClassLike ? K : never]: T[K];
2144
+ }
2145
+ | keyof {
2146
+ [K_1 in keyof T as Required<T>[K_1] extends FunctionLike ? K_1 : never]: T[K_1];
2147
+ }
2148
+ >,
2149
+ V extends Required<T>[K_2],
2150
+ A extends "set" | "get",
2151
+ >(
2152
+ object: T,
2153
+ methodKey: K_2,
2154
+ accessType: A,
2155
+ ): A extends "get" ? SpiedGetter<V> : A extends "set" ? SpiedSetter<V> : never;
2156
+ <
2157
+ T_1 extends object,
2158
+ K_5 extends
2159
+ | keyof {
2160
+ [K_3 in keyof T_1 as Required<T_1>[K_3] extends ClassLike ? K_3 : never]: T_1[K_3];
2161
+ }
2162
+ | keyof {
2163
+ [K_4 in keyof T_1 as Required<T_1>[K_4] extends FunctionLike ? K_4 : never]: T_1[K_4];
2164
+ },
2165
+ V_1 extends Required<T_1>[K_5],
2166
+ >(
2167
+ object: T_1,
2168
+ methodKey: K_5,
2169
+ ): V_1 extends ClassLike | FunctionLike ? Spied<V_1> : never;
2170
+ };
2171
+
2172
+ export interface UnknownClass {
2173
+ new (...args: unknown[]): unknown;
2174
+ }
2175
+
2176
+ export type UnknownFunction = (...args: unknown[]) => unknown;
2288
2177
  }