-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Expand file tree
/
Copy pathtest.d.ts
More file actions
2410 lines (2226 loc) · 75.4 KB
/
test.d.ts
File metadata and controls
2410 lines (2226 loc) · 75.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* To run tests, run `bun test`
*
* @example
*
* ```bash
* $ bun test
* ```
*
* @example
* ```bash
* $ bun test <filename>
* ```
*/
declare module "bun:test" {
export type Mock<T extends (...args: any[]) => any> = JestMock.Mock<T>;
export const mock: {
<T extends (...args: any[]) => any>(Function?: T): Mock<T>;
/**
* Replace the module `id` with the return value of `factory`.
*
* This is useful for mocking modules.
*
* If the module is already loaded, exports are overwritten with the return
* value of `factory`. If the export didn't exist before, it will not be
* added to existing import statements. This is due to how ESM works.
*
* @param id module ID to mock
* @param factory a function returning an object that will be used as the exports of the mocked module
*
* @example
* ```ts
* import { mock } from "bun:test";
*
* mock.module("fs/promises", () => {
* return {
* readFile: () => Promise.resolve("hello world"),
* };
* });
*
* import { readFile } from "fs/promises";
*
* console.log(await readFile("hello.txt", "utf8")); // hello world
* ```
*/
module(id: string, factory: () => any): void | Promise<void>;
/**
* Restore the previous value of mocks.
*/
restore(): void;
/**
* Reset all mock function state (calls, results, etc.) without restoring their original implementation.
*/
clearAllMocks(): void;
};
/**
* Control the system time used by:
* - `Date.now()`
* - `new Date()`
* - `Intl.DateTimeFormat().format()`
*
* In the future, we may add support for more functions, but we haven't done that yet.
*
* @param now The time to set the system time to. If not provided, the system time will be reset.
* @returns `this`
* @since v0.6.13
*
* ## Set Date to a specific time
*
* ```js
* import { setSystemTime } from 'bun:test';
*
* setSystemTime(new Date('2020-01-01T00:00:00.000Z'));
* console.log(new Date().toISOString()); // 2020-01-01T00:00:00.000Z
* ```
* ## Reset Date to the current time
*
* ```js
* import { setSystemTime } from 'bun:test';
*
* setSystemTime();
* ```
*/
export function setSystemTime(now?: Date | number): ThisType<void>;
export namespace jest {
function restoreAllMocks(): void;
function clearAllMocks(): void;
function resetAllMocks(): void;
function fn<T extends (...args: any[]) => any>(func?: T): Mock<T>;
function setSystemTime(now?: number | Date): void;
function setTimeout(milliseconds: number): void;
function useFakeTimers(options?: { now?: number | Date }): typeof vi;
function useRealTimers(): typeof vi;
function advanceTimersByTime(milliseconds: number): typeof vi;
function advanceTimersToNextTimer(): typeof vi;
function runAllTimers(): typeof vi;
function runOnlyPendingTimers(): typeof vi;
function getTimerCount(): number;
function clearAllTimers(): void;
function isFakeTimers(): boolean;
function spyOn<T extends object, K extends keyof T>(
obj: T,
methodOrPropertyValue: K,
): Mock<Extract<T[K], (...args: any[]) => any>>;
/**
* Constructs the type of a mock function, e.g. the return type of `jest.fn()`.
*/
type Mock<T extends (...args: any[]) => any = (...args: any[]) => any> = JestMock.Mock<T>;
/**
* Wraps a class, function or object type with Jest mock type definitions.
*/
// type Mocked<T extends object> = JestMock.Mocked<T>;
/**
* Wraps a class type with Jest mock type definitions.
*/
// type MockedClass<T extends JestMock.ClassLike> = JestMock.MockedClass<T>;
/**
* Wraps a function type with Jest mock type definitions.
*/
// type MockedFunction<T extends (...args: any[]) => any> = JestMock.MockedFunction<T>;
/**
* Wraps an object type with Jest mock type definitions.
*/
// type MockedObject<T extends object> = JestMock.MockedObject<T>;
/**
* Constructs the type of a replaced property.
*/
type Replaced<T> = JestMock.Replaced<T>;
/**
* Constructs the type of a spied class or function.
*/
type Spied<T extends JestMock.ClassLike | ((...args: any[]) => any)> = JestMock.Spied<T>;
/**
* Constructs the type of a spied class.
*/
type SpiedClass<T extends JestMock.ClassLike> = JestMock.SpiedClass<T>;
/**
* Constructs the type of a spied function.
*/
type SpiedFunction<T extends (...args: any[]) => any> = JestMock.SpiedFunction<T>;
/**
* Constructs the type of a spied getter.
*/
type SpiedGetter<T> = JestMock.SpiedGetter<T>;
/**
* Constructs the type of a spied setter.
*/
type SpiedSetter<T> = JestMock.SpiedSetter<T>;
}
/**
* Create a spy on an object property or method
*/
export function spyOn<T extends object, K extends keyof T>(
obj: T,
methodOrPropertyValue: K,
): Mock<Extract<T[K], (...args: any[]) => any>>;
/**
* Vitest-compatible mocking utilities
* Provides Vitest-style mocking API for easier migration from Vitest to Bun
*/
export const vi: {
/**
* Create a mock function
*/
fn: typeof jest.fn;
/**
* Create a spy on an object property or method
*/
spyOn: typeof spyOn;
/**
* Mock a module
*/
mock: typeof mock.module;
/**
* Restore all mocks to their original implementation
*/
restoreAllMocks: typeof jest.restoreAllMocks;
/**
* Clear all mock state (calls, results, etc.) without restoring original implementation
*/
clearAllMocks: typeof jest.clearAllMocks;
resetAllMocks: typeof jest.resetAllMocks;
useFakeTimers: typeof jest.useFakeTimers;
useRealTimers: typeof jest.useRealTimers;
advanceTimersByTime: typeof jest.advanceTimersByTime;
advanceTimersToNextTimer: typeof jest.advanceTimersToNextTimer;
runAllTimers: typeof jest.runAllTimers;
runOnlyPendingTimers: typeof jest.runOnlyPendingTimers;
getTimerCount: typeof jest.getTimerCount;
clearAllTimers: typeof jest.clearAllTimers;
isFakeTimers: typeof jest.isFakeTimers;
};
interface FunctionLike {
readonly name: string;
}
type DescribeLabel = number | string | Function | FunctionLike;
/**
* Describes a group of related tests.
*
* @example
* function sum(a, b) {
* return a + b;
* }
* describe("sum()", () => {
* test("can sum two values", () => {
* expect(sum(1, 1)).toBe(2);
* });
* });
*
* @param label the label for the tests
* @param fn the function that defines the tests
*
* @category Testing
*/
export interface Describe<T extends Readonly<any[]>> {
(fn: () => void): void;
(label: DescribeLabel, fn: (...args: T) => void): void;
/**
* Skips all other tests, except this group of tests.
*/
only: Describe<T>;
/**
* Skips this group of tests.
*/
skip: Describe<T>;
/**
* Marks this group of tests as to be written or to be fixed.
*/
todo: Describe<T>;
/**
* Marks this group of tests to be executed concurrently.
*/
concurrent: Describe<T>;
/**
* Marks this group of tests to be executed serially (one after another),
* even when the --concurrent flag is used.
*/
serial: Describe<T>;
/**
* Runs this group of tests, only if `condition` is true.
*
* This is the opposite of `describe.skipIf()`.
*
* @param condition if these tests should run
*/
if(condition: boolean): Describe<T>;
/**
* Skips this group of tests, if `condition` is true.
*
* @param condition if these tests should be skipped
*/
skipIf(condition: boolean): Describe<T>;
/**
* Marks this group of tests as to be written or to be fixed, if `condition` is true.
*
* @param condition if these tests should be skipped
*/
todoIf(condition: boolean): Describe<T>;
/**
* Returns a function that runs for each item in `table`.
*
* @param table Array of Arrays with the arguments that are passed into the test fn for each row.
*/
each<T extends Readonly<[any, ...any[]]>>(table: readonly T[]): Describe<[...T]>;
each<T extends any[]>(table: readonly T[]): Describe<[...T]>;
each<const T>(table: T[]): Describe<[T]>;
}
/**
* Describes a group of related tests.
*
* @example
* function sum(a, b) {
* return a + b;
* }
* describe("sum()", () => {
* test("can sum two values", () => {
* expect(sum(1, 1)).toBe(2);
* });
* });
*
* @param label the label for the tests
* @param fn the function that defines the tests
*/
export const describe: Describe<[]>;
/**
* Skips a group of related tests.
*
* This is equivalent to calling `describe.skip()`.
*
* @param label the label for the tests
* @param fn the function that defines the tests
*/
export const xdescribe: Describe<[]>;
type HookOptions = number | { timeout?: number };
/**
* Runs a function, once, before all the tests.
*
* This is useful for running set up tasks, like initializing
* a global variable or connecting to a database.
*
* If this function throws, tests will not run in this file.
*
* @example
* let database;
* beforeAll(async () => {
* database = await connect("localhost");
* });
*
* @param fn the function to run
*/
export function beforeAll(
fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
options?: HookOptions,
): void;
/**
* Runs a function before each test.
*
* This is useful for running set up tasks, like initializing
* a global variable or connecting to a database.
*
* If this function throws, the test will not run.
*
* @param fn the function to run
*/
export function beforeEach(
fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
options?: HookOptions,
): void;
/**
* Runs a function, once, after all the tests.
*
* This is useful for running clean up tasks, like closing
* a socket or deleting temporary files.
*
* @example
* let database;
* afterAll(async () => {
* if (database) {
* await database.close();
* }
* });
*
* @param fn the function to run
*/
export function afterAll(
fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
options?: HookOptions,
): void;
/**
* Runs a function after each test.
*
* This is useful for running clean up tasks, like closing
* a socket or deleting temporary files.
*
* @param fn the function to run
*/
export function afterEach(
fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
options?: HookOptions,
): void;
/**
* Runs a function after a test finishes, including after all afterEach hooks.
*
* This is useful for cleanup tasks that need to run at the very end of a test,
* after all other hooks have completed.
*
* Can only be called inside a test, not in describe blocks.
*
* Works inside concurrent tests when `onTestFinished()` is called
* synchronously from the test callback body (including microtasks drained
* before the first suspension point). Registrations made after yielding to
* a later event-loop turn — for example after `await`ing a timer — may
* not resolve which concurrent sequence they belong to.
*
* @example
* test("my test", () => {
* onTestFinished(() => {
* // This runs after all afterEach hooks
* console.log("Test finished!");
* });
* });
*
* @param fn the function to run
*/
export function onTestFinished(
fn: (() => void | Promise<unknown>) | ((done: (err?: unknown) => void) => void),
options?: HookOptions,
): void;
/**
* Sets the default timeout for all tests in the current file. If a test specifies a timeout, it will
* override this value. The default timeout is 5000ms (5 seconds).
*
* @param milliseconds the number of milliseconds for the default timeout
*/
export function setDefaultTimeout(milliseconds: number): void;
export interface TestOptions {
/**
* Sets the timeout for the test in milliseconds.
*
* If the test does not complete within this time, the test will fail with:
* ```ts
* 'Timeout: test {name} timed out after 5000ms'
* ```
*
* @default 5000 // 5 seconds
*/
timeout?: number;
/**
* Sets the number of times to retry the test if it fails.
*
* @default 0
*/
retry?: number;
/**
* Sets the number of times to repeat the test, regardless of whether it passed or failed.
*
* @default 0
*/
repeats?: number;
}
namespace __internal {
type IfNeverThenElse<T, Else> = [T] extends [never] ? Else : T;
type IsTuple<T> = T extends readonly unknown[]
? number extends T["length"]
? false // It's an array with unknown length, not a tuple
: true // It's an array with a fixed length (a tuple)
: false; // Not an array at all
/**
* Accepts `[1, 2, 3] | ["a", "b", "c"]` and returns `[1 | "a", 2 | "b", 3 | "c"]`
*/
type Flatten<T, Copy extends T = T> = { [Key in keyof T]: Copy[Key] };
}
/**
* Runs a test.
*
* @example
* test("can check if using Bun", () => {
* expect(Bun).toBeDefined();
* });
*
* test("can make a fetch() request", async () => {
* const response = await fetch("https://example.com/");
* expect(response.ok).toBe(true);
* });
*
* test("can set a timeout", async () => {
* await Bun.sleep(100);
* }, 50); // or { timeout: 50 }
*
* @param label the label for the test
* @param fn the test function
* @param options the test timeout or options
*
* @category Testing
*/
export interface Test<T extends ReadonlyArray<unknown>> {
(
label: string,
fn: (
...args: __internal.IsTuple<T> extends true
? [...table: __internal.Flatten<T>, done: (err?: unknown) => void]
: T
) => void | Promise<unknown>,
/**
* - If a `number`, sets the timeout for the test in milliseconds.
* - If an `object`, sets the options for the test.
* - `timeout` sets the timeout for the test in milliseconds.
* - `retry` sets the number of times to retry the test if it fails.
* - `repeats` sets the number of times to repeat the test, regardless of whether it passed or failed.
*/
options?: number | TestOptions,
): void;
/**
* Skips all other tests, except this test.
*/
only: Test<T>;
/**
* Skips this test.
*/
skip: Test<T>;
/**
* Marks this test as to be written or to be fixed.
*
* These tests will not be executed unless the `--todo` flag is passed. With the flag,
* if the test passes, the test will be marked as `fail` in the results; you will have to
* remove the `.todo` or check that your test
* is implemented correctly.
*/
todo: Test<T>;
/**
* Marks this test as failing.
*
* Use `test.failing` when you are writing a test and expecting it to fail.
* These tests will behave the other way normal tests do. If failing test
* will throw any errors then it will pass. If it does not throw it will
* fail.
*
* `test.failing` is very similar to {@link test.todo} except that it always
* runs, regardless of the `--todo` flag.
*/
failing: Test<T>;
/**
* Runs the test concurrently with other concurrent tests.
*/
concurrent: Test<T>;
/**
* Forces the test to run serially (not in parallel),
* even when the --concurrent flag is used.
*/
serial: Test<T>;
/**
* Runs this test, if `condition` is true.
*
* This is the opposite of `test.skipIf()`.
*
* @param condition if the test should run
*/
if(condition: boolean): Test<T>;
/**
* Skips this test, if `condition` is true.
*
* @param condition if the test should be skipped
*/
skipIf(condition: boolean): Test<T>;
/**
* Marks this test as to be written or to be fixed, if `condition` is true.
*
* @param condition if the test should be marked TODO
*/
todoIf(condition: boolean): Test<T>;
/**
* Marks this test as failing, if `condition` is true.
*
* @param condition if the test should be marked as failing
*/
failingIf(condition: boolean): Test<T>;
/**
* Runs the test concurrently with other concurrent tests, if `condition` is true.
*
* @param condition if the test should run concurrently
*/
concurrentIf(condition: boolean): Test<T>;
/**
* Forces the test to run serially (not in parallel), if `condition` is true.
* This applies even when the --concurrent flag is used.
*
* @param condition if the test should run serially
*/
serialIf(condition: boolean): Test<T>;
/**
* Returns a function that runs for each item in `table`.
*
* @param table Array of Arrays with the arguments that are passed into the test fn for each row.
*/
each<T extends Readonly<[unknown, ...unknown[]]>>(table: readonly T[]): Test<T>;
each<T extends unknown[]>(table: readonly T[]): Test<T>;
each<const T>(table: T[]): Test<[T]>;
}
/**
* Runs a test.
*
* @example
* test("can check if using Bun", () => {
* expect(Bun).toBeDefined();
* });
*
* test("can make a fetch() request", async () => {
* const response = await fetch("https://example.com/");
* expect(response.ok).toBe(true);
* });
*
* @param label the label for the test
* @param fn the test function
*/
export const test: Test<[]>;
export { test as it, xtest as xit };
/**
* Skips a test.
*
* This is equivalent to calling `test.skip()`.
*
* @param label the label for the test
* @param fn the test function
*/
export const xtest: Test<[]>;
/**
* Asserts that a value matches some criteria.
*
* @link https://jestjs.io/docs/expect#reference
* @example
* expect(1 + 1).toBe(2);
* expect([1,2,3]).toContain(2);
* expect(null).toBeNull();
*
* @param actual The actual (received) value
*/
export const expect: Expect;
type ExpectNot = Omit<AsymmetricMatchers, keyof AsymmetricMatchersBuiltin> & AsymmetricMatchersBuiltinNegated;
export interface Expect extends AsymmetricMatchers {
// the `expect()` callable signature
/**
* @param actual the actual value
* @param customFailMessage an optional custom message to display if the test fails.
* */
(actual?: never, customFailMessage?: string): Matchers<undefined>;
<T = unknown>(actual: T, customFailMessage?: string): Matchers<T>;
<T = unknown>(actual?: T, customFailMessage?: string): Matchers<T | undefined>;
/**
* Access to negated asymmetric matchers.
*
* @example
* expect("abc").toEqual(expect.stringContaining("abc")); // will pass
* expect("abc").toEqual(expect.not.stringContaining("abc")); // will fail
*/
not: ExpectNot;
/**
* Create an asymmetric matcher for a promise resolved value.
*
* @example
* expect(Promise.resolve("value")).toEqual(expect.resolvesTo.stringContaining("value")); // will pass
* expect(Promise.reject("value")).toEqual(expect.resolvesTo.stringContaining("value")); // will fail
* expect("value").toEqual(expect.resolvesTo.stringContaining("value")); // will fail
*/
resolvesTo: AsymmetricMatchers;
/**
* Create an asymmetric matcher for a promise rejected value.
*
* @example
* expect(Promise.reject("error")).toEqual(expect.rejectsTo.stringContaining("error")); // will pass
* expect(Promise.resolve("error")).toEqual(expect.rejectsTo.stringContaining("error")); // will fail
* expect("error").toEqual(expect.rejectsTo.stringContaining("error")); // will fail
*/
rejectsTo: AsymmetricMatchers;
/**
* Register new custom matchers.
* @param matchers An object containing the matchers to register, where each key is the matcher name, and its value the implementation function.
* The function must satisfy: `(actualValue, ...matcherInstantiationArguments) => { pass: true|false, message: () => string }`
*
* @example
* expect.extend({
* toBeWithinRange(actual, min, max) {
* if (typeof actual !== 'number' || typeof min !== 'number' || typeof max !== 'number')
* throw new Error('Invalid usage');
* const pass = actual >= min && actual <= max;
* return {
* pass: pass,
* message: () => `expected ${this.utils.printReceived(actual)} ` +
* (pass ? `not to be`: `to be`) + ` within range ${this.utils.printExpected(`${min} .. ${max}`)}`,
* };
* },
* });
*
* test('some test', () => {
* expect(50).toBeWithinRange(0, 100); // will pass
* expect(50).toBeWithinRange(100, 200); // will fail
* expect(50).toBe(expect.toBeWithinRange(0, 100)); // will pass
* expect(50).toBe(expect.not.toBeWithinRange(100, 200)); // will pass
* });
*/
extend<M>(matchers: ExpectExtendMatchers<M>): void;
/**
* Throw an error if this function is called.
*
* @param msg Optional message to display if the test fails
* @returns never
*
* @example
* ```ts
* import { expect, test } from "bun:test";
*
* test("!!abc!! is not a module", () => {
* try {
* require("!!abc!!");
* expect.unreachable();
* } catch(e) {
* expect(e.name).not.toBe("UnreachableError");
* }
* });
* ```
*/
unreachable(msg?: string | Error): never;
/**
* Ensures that an assertion is made.
*
* Not supported in concurrent tests — use `test.serial` or remove
* `.concurrent` from the enclosing test. Unlike `onTestFinished()`,
* this cannot be resolved to the owning sequence across `await`
* boundaries, so it throws unconditionally rather than silently
* miscounting.
*/
hasAssertions(): void;
/**
* Ensures that a specific number of assertions are made.
*
* Not supported in concurrent tests — use `test.serial` or remove
* `.concurrent` from the enclosing test. Unlike `onTestFinished()`,
* this cannot be resolved to the owning sequence across `await`
* boundaries, so it throws unconditionally rather than silently
* miscounting.
*/
assertions(neededAssertions: number): void;
}
/**
* You can extend this interface with declaration merging, in order to add type support for custom matchers.
* @template T Type of the actual value
*
* @example
* // my_modules.d.ts
* interface MyCustomMatchers {
* toBeWithinRange(floor: number, ceiling: number): any;
* }
* declare module "bun:test" {
* interface Matchers<T> extends MyCustomMatchers {}
* interface AsymmetricMatchers extends MyCustomMatchers {}
* }
*
* @example
* // my_modules.d.ts (alternatively)
* declare module "bun:test" {
* interface Matchers<T> {
* toBeWithinRange(floor: number, ceiling: number): any;
* }
* interface AsymmetricMatchers {
* toBeWithinRange(floor: number, ceiling: number): any;
* }
* }
*/
export interface Matchers<T = unknown> extends MatchersBuiltin<T> {}
/**
* You can extend this interface with declaration merging, in order to add type support for custom asymmetric matchers.
* @example
* // my_modules.d.ts
* interface MyCustomMatchers {
* toBeWithinRange(floor: number, ceiling: number): any;
* }
* declare module "bun:test" {
* interface Matchers<T> extends MyCustomMatchers {}
* interface AsymmetricMatchers extends MyCustomMatchers {}
* }
*
* @example
* // my_modules.d.ts (alternatively)
* declare module "bun:test" {
* interface Matchers<T> {
* toBeWithinRange(floor: number, ceiling: number): any;
* }
* interface AsymmetricMatchers {
* toBeWithinRange(floor: number, ceiling: number): any;
* }
* }
*/
export interface AsymmetricMatchers extends AsymmetricMatchersBuiltin {}
export interface AsymmetricMatchersBuiltin {
/**
* Matches anything that was created with the given constructor.
* You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
*
* @example
*
* function randocall(fn) {
* return fn(Math.floor(Math.random() * 6 + 1));
* }
*
* test('randocall calls its callback with a number', () => {
* const mock = jest.fn();
* randocall(mock);
* expect(mock).toBeCalledWith(expect.any(Number));
* });
*/
any(constructor: ((...args: any[]) => any) | { new (...args: any[]): any }): AsymmetricMatcher;
/**
* Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead
* of a literal value. For example, if you want to check that a mock function is called with a
* non-null argument:
*
* @example
*
* test('map calls its argument with a non-null argument', () => {
* const mock = jest.fn();
* [1].map(x => mock(x));
* expect(mock).toBeCalledWith(expect.anything());
* });
*/
anything(): AsymmetricMatcher;
/**
* Matches any array made up entirely of elements in the provided array.
* You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
*
* Optionally, you can provide a type for the elements via a generic.
*/
arrayContaining<E = any>(arr: readonly E[]): AsymmetricMatcher;
/**
* Matches any object that recursively matches the provided keys.
* This is often handy in conjunction with other asymmetric matchers.
*
* Optionally, you can provide a type for the object via a generic.
* This ensures that the object contains the desired structure.
*/
objectContaining(obj: object): AsymmetricMatcher;
/**
* Matches any received string that contains the exact expected string
*/
stringContaining(str: string | String): AsymmetricMatcher;
/**
* Matches any string that contains the exact provided string
*/
stringMatching(regex: string | String | RegExp): AsymmetricMatcher;
/**
* Useful when comparing floating point numbers in object properties or array item.
* If you need to compare a number, use `.toBeCloseTo` instead.
*
* The optional `numDigits` argument limits the number of digits to check after the decimal point.
* For the default value 2, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`).
*/
closeTo(num: number, numDigits?: number): AsymmetricMatcher;
}
interface AsymmetricMatchersBuiltinNegated {
/**
* Create an asymmetric matcher that will fail on a promise resolved value that matches the chained matcher.
*
* @example
* expect(Promise.resolve("value")).toEqual(expect.not.resolvesTo.stringContaining("value")); // will fail
* expect(Promise.reject("value")).toEqual(expect.not.resolvesTo.stringContaining("value")); // will pass
* expect("value").toEqual(expect.not.resolvesTo.stringContaining("value")); // will pass
*/
resolvesTo: ExpectNot;
/**
* Create an asymmetric matcher that will fail on a promise rejected value that matches the chained matcher.
*
* @example
* expect(Promise.reject("value")).toEqual(expect.not.rejectsTo.stringContaining("value")); // will fail
* expect(Promise.resolve("value")).toEqual(expect.not.rejectsTo.stringContaining("value")); // will pass
* expect("value").toEqual(expect.not.rejectsTo.stringContaining("value")); // will pass
*/
rejectsTo: ExpectNot;
/**
* `expect.not.arrayContaining(array)` matches a received array which
* does not contain all of the elements in the expected array. That is,
* the expected array is not a subset of the received array. It is the
* inverse of `expect.arrayContaining`.
*
* Optionally, you can provide a type for the elements via a generic.
*/
arrayContaining<E = any>(arr: readonly E[]): AsymmetricMatcher;
/**
* `expect.not.objectContaining(object)` matches any received object
* that does not recursively match the expected properties. That is, the
* expected object is not a subset of the received object. Therefore,
* it matches a received object which contains properties that are not
* in the expected object. It is the inverse of `expect.objectContaining`.
*
* Optionally, you can provide a type for the object via a generic.
* This ensures that the object contains the desired structure.
*/
objectContaining(obj: object): AsymmetricMatcher;
/**
* `expect.not.stringContaining(string)` matches the received string
* that does not contain the exact expected string. It is the inverse of
* `expect.stringContaining`.
*/
stringContaining(str: string | String): AsymmetricMatcher;
/**
* `expect.not.stringMatching(string | regexp)` matches the received
* string that does not match the expected regexp. It is the inverse of
* `expect.stringMatching`.
*/
stringMatching(str: string | String | RegExp): AsymmetricMatcher;
/**
* `expect.not.closeTo` matches a number not close to the provided value.
* Useful when comparing floating point numbers in object properties or array item.
* It is the inverse of `expect.closeTo`.
*/
closeTo(num: number, numDigits?: number): AsymmetricMatcher;
}
export interface MatchersBuiltin<T = unknown> {
/**
* Negates the result of a subsequent assertion.
* If you know how to test something, `.not` lets you test its opposite.
*
* @example
* expect(1).not.toBe(0);
* expect(null).not.toBeNull();
*
* @example
* expect(42).toEqual(42); // will pass
* expect(42).not.toEqual(42); // will fail
*/
not: Matchers<unknown>;
/**
* Expects the value to be a promise that resolves.
*
* @example
* expect(Promise.resolve(1)).resolves.toBe(1);
*/
resolves: Matchers<Awaited<T>>;
/**
* Expects the value to be a promise that rejects.
*
* @example
* expect(Promise.reject("error")).rejects.toBe("error");
*/
rejects: Matchers<unknown>;
/**
* Assertion which passes.
*
* @link https://jest-extended.jestcommunity.dev/docs/matchers/pass
* @example
* expect().pass();
* expect().pass("message is optional");
* expect().not.pass();
* expect().not.pass("hi");
*
* @param message the message to display if the test fails (optional)
*/
pass: (message?: string) => void;
/**
* Assertion which fails.
*
* @link https://jest-extended.jestcommunity.dev/docs/matchers/fail
* @example
* expect().fail();
* expect().fail("message is optional");
* expect().not.fail();
* expect().not.fail("hi");
*/
fail: (message?: string) => void;
/**
* Asserts that a value equals what is expected.
*
* - For non-primitive values, like objects and arrays,
* use `toEqual()` instead.
* - For floating-point numbers, use `toBeCloseTo()` instead.
*
* @example
* expect(100 + 23).toBe(123);
* expect("d" + "og").toBe("dog");
* expect([123]).toBe([123]); // fail, use toEqual()
* expect(3 + 0.14).toBe(3.14); // fail, use toBeCloseTo()
*
* // TypeScript errors:
* expect("hello").toBe(3.14); // typescript error + fail
* expect("hello").toBe<number>(3.14); // no typescript error, but still fails
*
* @param expected the expected value
*/
toBe(expected: T): void;
toBe<X = T>(expected: NoInfer<X>): void;
/**
* Asserts that a number is odd.
*
* @link https://jest-extended.jestcommunity.dev/docs/matchers/number/#tobeodd