UNPKG

71.5 kBTypeScriptView Raw
1// Type definitions for Jest 29.5
2// Project: https://jestjs.io/
3// Definitions by: Asana (https://asana.com)
4// Ivo Stratev <https://github.com/NoHomey>
5// jwbay <https://github.com/jwbay>
6// Alexey Svetliakov <https://github.com/asvetliakov>
7// Alex Jover Morales <https://github.com/alexjoverm>
8// Allan Lukwago <https://github.com/epicallan>
9// Ika <https://github.com/ikatyang>
10// Waseem Dahman <https://github.com/wsmd>
11// Jamie Mason <https://github.com/JamieMason>
12// Douglas Duteil <https://github.com/douglasduteil>
13// Ahn <https://github.com/ahnpnl>
14// Jeff Lau <https://github.com/UselessPickles>
15// Andrew Makarov <https://github.com/r3nya>
16// Martin Hochel <https://github.com/hotell>
17// Sebastian Sebald <https://github.com/sebald>
18// Andy <https://github.com/andys8>
19// Antoine Brault <https://github.com/antoinebrault>
20// Gregor Stamać <https://github.com/gstamac>
21// ExE Boss <https://github.com/ExE-Boss>
22// Alex Bolenok <https://github.com/quassnoi>
23// Mario Beltrán Alarcón <https://github.com/Belco90>
24// Tony Hallett <https://github.com/tonyhallett>
25// Jason Yu <https://github.com/ycmjason>
26// Pawel Fajfer <https://github.com/pawfa>
27// Alexandre Germain <https://github.com/gerkindev>
28// Adam Jones <https://github.com/domdomegg>
29// Tom Mrazauskas <https://github.com/mrazauskas>
30// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
31// Minimum TypeScript Version: 4.3
32
33declare var beforeAll: jest.Lifecycle;
34declare var beforeEach: jest.Lifecycle;
35declare var afterAll: jest.Lifecycle;
36declare var afterEach: jest.Lifecycle;
37declare var describe: jest.Describe;
38declare var fdescribe: jest.Describe;
39declare var xdescribe: jest.Describe;
40declare var it: jest.It;
41declare var fit: jest.It;
42declare var xit: jest.It;
43declare var test: jest.It;
44declare var xtest: jest.It;
45
46declare const expect: jest.Expect;
47
48// Remove once https://github.com/microsoft/TypeScript/issues/53255 is fixed.
49type ExtractEachCallbackArgs<T extends ReadonlyArray<any>> = {
50 1: [T[0]];
51 2: [T[0], T[1]];
52 3: [T[0], T[1], T[2]];
53 4: [T[0], T[1], T[2], T[3]];
54 5: [T[0], T[1], T[2], T[3], T[4]];
55 6: [T[0], T[1], T[2], T[3], T[4], T[5]];
56 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6]];
57 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7]];
58 9: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8]];
59 10: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], T[8], T[9]];
60 fallback: Array<T extends ReadonlyArray<infer U> ? U : any>;
61}[T extends Readonly<[any]>
62 ? 1
63 : T extends Readonly<[any, any]>
64 ? 2
65 : T extends Readonly<[any, any, any]>
66 ? 3
67 : T extends Readonly<[any, any, any, any]>
68 ? 4
69 : T extends Readonly<[any, any, any, any, any]>
70 ? 5
71 : T extends Readonly<[any, any, any, any, any, any]>
72 ? 6
73 : T extends Readonly<[any, any, any, any, any, any, any]>
74 ? 7
75 : T extends Readonly<[any, any, any, any, any, any, any, any]>
76 ? 8
77 : T extends Readonly<[any, any, any, any, any, any, any, any, any]>
78 ? 9
79 : T extends Readonly<[any, any, any, any, any, any, any, any, any, any]>
80 ? 10
81 : 'fallback'];
82
83type FakeableAPI =
84 | 'Date'
85 | 'hrtime'
86 | 'nextTick'
87 | 'performance'
88 | 'queueMicrotask'
89 | 'requestAnimationFrame'
90 | 'cancelAnimationFrame'
91 | 'requestIdleCallback'
92 | 'cancelIdleCallback'
93 | 'setImmediate'
94 | 'clearImmediate'
95 | 'setInterval'
96 | 'clearInterval'
97 | 'setTimeout'
98 | 'clearTimeout';
99
100interface FakeTimersConfig {
101 /**
102 * If set to `true` all timers will be advanced automatically
103 * by 20 milliseconds every 20 milliseconds. A custom time delta
104 * may be provided by passing a number.
105 *
106 * @defaultValue
107 * The default is `false`.
108 */
109 advanceTimers?: boolean | number;
110 /**
111 * List of names of APIs (e.g. `Date`, `nextTick()`, `setImmediate()`,
112 * `setTimeout()`) that should not be faked.
113 *
114 * @defaultValue
115 * The default is `[]`, meaning all APIs are faked.
116 */
117 doNotFake?: FakeableAPI[];
118 /**
119 * Sets current system time to be used by fake timers.
120 *
121 * @defaultValue
122 * The default is `Date.now()`.
123 */
124 now?: number | Date;
125 /**
126 * The maximum number of recursive timers that will be run when calling
127 * `jest.runAllTimers()`.
128 *
129 * @defaultValue
130 * The default is `100_000` timers.
131 */
132 timerLimit?: number;
133 /**
134 * Use the old fake timers implementation instead of one backed by
135 * [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).
136 *
137 * @defaultValue
138 * The default is `false`.
139 */
140 legacyFakeTimers?: false;
141}
142
143interface LegacyFakeTimersConfig {
144 /**
145 * Use the old fake timers implementation instead of one backed by
146 * [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).
147 *
148 * @defaultValue
149 * The default is `false`.
150 */
151 legacyFakeTimers?: true;
152}
153
154declare namespace jest {
155 /**
156 * Disables automatic mocking in the module loader.
157 */
158 function autoMockOff(): typeof jest;
159 /**
160 * Enables automatic mocking in the module loader.
161 */
162 function autoMockOn(): typeof jest;
163 /**
164 * Clears the mock.calls and mock.instances properties of all mocks.
165 * Equivalent to calling .mockClear() on every mocked function.
166 */
167 function clearAllMocks(): typeof jest;
168 /**
169 * Use the automatic mocking system to generate a mocked version of the given module.
170 */
171 // eslint-disable-next-line no-unnecessary-generics
172 function createMockFromModule<T>(moduleName: string): T;
173 /**
174 * Resets the state of all mocks.
175 * Equivalent to calling .mockReset() on every mocked function.
176 */
177 function resetAllMocks(): typeof jest;
178 /**
179 * Restores all mocks and replaced properties back to their original value.
180 * Equivalent to calling `.mockRestore()` on every mocked function
181 * and `.restore()` on every replaced property.
182 *
183 * Beware that `jest.restoreAllMocks()` only works when the mock was created
184 * with `jest.spyOn()`; other mocks will require you to manually restore them.
185 */
186 function restoreAllMocks(): typeof jest;
187 /**
188 * Removes any pending timers from the timer system. If any timers have
189 * been scheduled, they will be cleared and will never have the opportunity
190 * to execute in the future.
191 */
192 function clearAllTimers(): void;
193 /**
194 * Returns the number of fake timers still left to run.
195 */
196 function getTimerCount(): number;
197 /**
198 * Set the current system time used by fake timers. Simulates a user
199 * changing the system clock while your program is running. It affects the
200 * current time but it does not in itself cause e.g. timers to fire; they
201 * will fire exactly as they would have done without the call to
202 * jest.setSystemTime().
203 *
204 * > Note: This function is only available when using modern fake timers
205 * > implementation
206 */
207 function setSystemTime(now?: number | Date): void;
208 /**
209 * When mocking time, Date.now() will also be mocked. If you for some
210 * reason need access to the real current time, you can invoke this
211 * function.
212 *
213 * > Note: This function is only available when using modern fake timers
214 * > implementation
215 */
216 function getRealSystemTime(): number;
217 /**
218 * Retrieves the seed value. It will be randomly generated for each test run
219 * or can be manually set via the `--seed` CLI argument.
220 */
221 function getSeed(): number;
222 /**
223 * Returns the current time in ms of the fake timer clock.
224 */
225 function now(): number;
226 /**
227 * Indicates that the module system should never return a mocked version
228 * of the specified module, including all of the specified module's dependencies.
229 */
230 function deepUnmock(moduleName: string): typeof jest;
231 /**
232 * Disables automatic mocking in the module loader.
233 */
234 function disableAutomock(): typeof jest;
235 /**
236 * Mocks a module with an auto-mocked version when it is being required.
237 */
238 // eslint-disable-next-line no-unnecessary-generics
239 function doMock<T = unknown>(moduleName: string, factory?: () => T, options?: MockOptions): typeof jest;
240 /**
241 * Indicates that the module system should never return a mocked version
242 * of the specified module from require() (e.g. that it should always return the real module).
243 */
244 function dontMock(moduleName: string): typeof jest;
245 /**
246 * Enables automatic mocking in the module loader.
247 */
248 function enableAutomock(): typeof jest;
249 /**
250 * Creates a mock function. Optionally takes a mock implementation.
251 */
252 function fn(): Mock;
253 /**
254 * Creates a mock function. Optionally takes a mock implementation.
255 */
256 function fn<T, Y extends any[], C = any>(implementation?: (this: C, ...args: Y) => T): Mock<T, Y, C>;
257 /**
258 * (renamed to `createMockFromModule` in Jest 26.0.0+)
259 * Use the automatic mocking system to generate a mocked version of the given module.
260 */
261 // eslint-disable-next-line no-unnecessary-generics
262 function genMockFromModule<T>(moduleName: string): T;
263 /**
264 * Returns `true` if test environment has been torn down.
265 *
266 * @example
267 *
268 * if (jest.isEnvironmentTornDown()) {
269 * // The Jest environment has been torn down, so stop doing work
270 * return;
271 * }
272 */
273 function isEnvironmentTornDown(): boolean;
274 /**
275 * Returns whether the given function is a mock function.
276 */
277 function isMockFunction(fn: any): fn is Mock;
278 /**
279 * Mocks a module with an auto-mocked version when it is being required.
280 */
281 // eslint-disable-next-line no-unnecessary-generics
282 function mock<T = unknown>(moduleName: string, factory?: () => T, options?: MockOptions): typeof jest;
283 /**
284 * Wraps types of the `source` object and its deep members with type definitions
285 * of Jest mock function. Pass `{shallow: true}` option to disable the deeply
286 * mocked behavior.
287 */
288 function mocked<T>(source: T, options?: { shallow: false }): MaybeMockedDeep<T>;
289 /**
290 * Wraps types of the `source` object with type definitions of Jest mock function.
291 */
292 function mocked<T>(source: T, options: { shallow: true }): MaybeMocked<T>;
293 /**
294 * Returns the actual module instead of a mock, bypassing all checks on
295 * whether the module should receive a mock implementation or not.
296 */
297 // eslint-disable-next-line no-unnecessary-generics
298 function requireActual<TModule extends {} = any>(moduleName: string): TModule;
299 /**
300 * Returns a mock module instead of the actual module, bypassing all checks
301 * on whether the module should be required normally or not.
302 */
303 // eslint-disable-next-line no-unnecessary-generics
304 function requireMock<TModule extends {} = any>(moduleName: string): TModule;
305 /**
306 * Resets the module registry - the cache of all required modules. This is
307 * useful to isolate modules where local state might conflict between tests.
308 */
309 function resetModules(): typeof jest;
310 /**
311 * Creates a sandbox registry for the modules that are loaded inside the callback function.
312 * This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests.
313 */
314 function isolateModules(fn: () => void): typeof jest;
315 /**
316 * Equivalent of `jest.isolateModules()` for async functions to be wrapped.
317 * The caller is expected to `await` the completion of `jest.isolateModulesAsync()`.
318 */
319 function isolateModulesAsync(fn: () => Promise<void>): Promise<void>;
320 /**
321 * Runs failed tests n-times until they pass or until the max number of retries is exhausted.
322 * This only works with jest-circus!
323 */
324 function retryTimes(numRetries: number, options?: { logErrorsBeforeRetry?: boolean }): typeof jest;
325 /**
326 * Replaces property on an object with another value.
327 *
328 * @remarks
329 * For mocking functions, and 'get' or 'set' accessors, use `jest.spyOn()` instead.
330 */
331 function replaceProperty<T extends object, K extends keyof T>(obj: T, key: K, value: T[K]): ReplaceProperty<T[K]>;
332 /**
333 * Exhausts tasks queued by `setImmediate()`.
334 *
335 * @remarks
336 * This function is only available when using legacy fake timers implementation.
337 */
338 function runAllImmediates(): void;
339 /**
340 * Exhausts the micro-task queue (i.e., tasks in Node.js scheduled with `process.nextTick()`).
341 */
342 function runAllTicks(): void;
343 /**
344 * Exhausts both the macro-task queue (i.e., tasks queued by `setTimeout()`, `setInterval()`
345 * and `setImmediate()`) and the micro-task queue (i.e., tasks in Node.js scheduled with
346 * `process.nextTick()`).
347 */
348 function runAllTimers(): void;
349 /**
350 * Asynchronous equivalent of `jest.runAllTimers()`. It also yields to the event loop,
351 * allowing any scheduled promise callbacks to execute _before_ running the timers.
352 *
353 * @remarks
354 * Not available when using legacy fake timers implementation.
355 */
356 function runAllTimersAsync(): Promise<void>;
357 /**
358 * Executes only the macro-tasks that are currently pending (i.e., only the tasks that
359 * have been queued by `setTimeout()`, `setInterval()` and `setImmediate()` up to this point).
360 */
361 function runOnlyPendingTimers(): void;
362 /**
363 * Asynchronous equivalent of `jest.runOnlyPendingTimers()`. It also yields to the event loop,
364 * allowing any scheduled promise callbacks to execute _before_ running the timers.
365 *
366 * @remarks
367 * Not available when using legacy fake timers implementation.
368 */
369 function runOnlyPendingTimersAsync(): Promise<void>;
370 /**
371 * Advances all timers by `msToRun` milliseconds. All pending macro-tasks that have been
372 * queued by `setTimeout()`, `setInterval()` and `setImmediate()`, and would be executed
373 * within this time frame will be executed.
374 */
375 function advanceTimersByTime(msToRun: number): void;
376 /**
377 * Asynchronous equivalent of `jest.advanceTimersByTime()`. It also yields to the event loop,
378 * allowing any scheduled promise callbacks to execute _before_ running the timers.
379 *
380 * @remarks
381 * Not available when using legacy fake timers implementation.
382 */
383 function advanceTimersByTimeAsync(msToRun: number): Promise<void>;
384 /**
385 * Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run.
386 * Optionally, you can provide steps, so it will run steps amount of next timeouts/intervals.
387 */
388 function advanceTimersToNextTimer(step?: number): void;
389 /**
390 * Asynchronous equivalent of `jest.advanceTimersToNextTimer()`. It also yields to the event loop,
391 * allowing any scheduled promise callbacks to execute _before_ running the timers.
392 *
393 * @remarks
394 * Not available when using legacy fake timers implementation.
395 */
396 function advanceTimersToNextTimerAsync(steps?: number): Promise<void>;
397 /**
398 * Explicitly supplies the mock object that the module system should return
399 * for the specified module.
400 */
401 // eslint-disable-next-line no-unnecessary-generics
402 function setMock<T>(moduleName: string, moduleExports: T): typeof jest;
403 /**
404 * Set the default timeout interval for tests and before/after hooks in milliseconds.
405 * Note: The default timeout interval is 5 seconds if this method is not called.
406 */
407 function setTimeout(timeout: number): typeof jest;
408 /**
409 * Creates a mock function similar to jest.fn but also tracks calls to `object[methodName]`
410 *
411 * Note: By default, jest.spyOn also calls the spied method. This is different behavior from most
412 * other test libraries.
413 *
414 * @example
415 *
416 * const video = require('./video');
417 *
418 * test('plays video', () => {
419 * const spy = jest.spyOn(video, 'play');
420 * const isPlaying = video.play();
421 *
422 * expect(spy).toHaveBeenCalled();
423 * expect(isPlaying).toBe(true);
424 *
425 * spy.mockReset();
426 * spy.mockRestore();
427 * });
428 */
429 function spyOn<
430 T extends {},
431 Key extends keyof T,
432 A extends PropertyAccessors<Key, T> = PropertyAccessors<Key, T>,
433 Value extends Required<T>[Key] = Required<T>[Key],
434 >(
435 object: T,
436 method: Key,
437 accessType: A,
438 ): A extends SetAccessor
439 ? SpyInstance<void, [Value]>
440 : A extends GetAccessor
441 ? SpyInstance<Value, []>
442 : Value extends Constructor
443 ? SpyInstance<InstanceType<Value>, ConstructorArgsType<Value>>
444 : Value extends Func
445 ? SpyInstance<ReturnType<Value>, ArgsType<Value>>
446 : never;
447 function spyOn<T extends {}, M extends ConstructorPropertyNames<Required<T>>>(
448 object: T,
449 method: M,
450 ): ConstructorProperties<Required<T>>[M] extends new (...args: any[]) => any
451 ? SpyInstance<
452 InstanceType<ConstructorProperties<Required<T>>[M]>,
453 ConstructorArgsType<ConstructorProperties<Required<T>>[M]>
454 >
455 : never;
456 function spyOn<T extends {}, M extends FunctionPropertyNames<Required<T>>>(
457 object: T,
458 method: M,
459 ): FunctionProperties<Required<T>>[M] extends Func
460 ? SpyInstance<ReturnType<FunctionProperties<Required<T>>[M]>, ArgsType<FunctionProperties<Required<T>>[M]>>
461 : never;
462 /**
463 * Indicates that the module system should never return a mocked version of
464 * the specified module from require() (e.g. that it should always return the real module).
465 */
466 function unmock(moduleName: string): typeof jest;
467 /**
468 * Instructs Jest to use fake versions of the standard timer functions.
469 */
470 function useFakeTimers(config?: FakeTimersConfig | LegacyFakeTimersConfig): typeof jest;
471 /**
472 * Instructs Jest to use the real versions of the standard timer functions.
473 */
474 function useRealTimers(): typeof jest;
475
476 interface MockOptions {
477 virtual?: boolean | undefined;
478 }
479
480 type MockableFunction = (...args: any[]) => any;
481 type MethodKeysOf<T> = { [K in keyof T]: T[K] extends MockableFunction ? K : never }[keyof T];
482 type PropertyKeysOf<T> = { [K in keyof T]: T[K] extends MockableFunction ? never : K }[keyof T];
483 type ArgumentsOf<T> = T extends (...args: infer A) => any ? A : never;
484 type ConstructorArgumentsOf<T> = T extends new (...args: infer A) => any ? A : never;
485 type ConstructorReturnType<T> = T extends new (...args: any) => infer C ? C : any;
486
487 interface MockWithArgs<T extends MockableFunction>
488 extends MockInstance<ReturnType<T>, ArgumentsOf<T>, ConstructorReturnType<T>> {
489 new (...args: ConstructorArgumentsOf<T>): T;
490 (...args: ArgumentsOf<T>): ReturnType<T>;
491 }
492 type MaybeMockedConstructor<T> = T extends new (...args: any[]) => infer R
493 ? MockInstance<R, ConstructorArgumentsOf<T>, R>
494 : T;
495 type MockedFn<T extends MockableFunction> = MockWithArgs<T> & { [K in keyof T]: T[K] };
496 type MockedFunctionDeep<T extends MockableFunction> = MockWithArgs<T> & MockedObjectDeep<T>;
497 type MockedObject<T> = MaybeMockedConstructor<T> & {
498 [K in MethodKeysOf<T>]: T[K] extends MockableFunction ? MockedFn<T[K]> : T[K];
499 } & { [K in PropertyKeysOf<T>]: T[K] };
500 type MockedObjectDeep<T> = MaybeMockedConstructor<T> & {
501 [K in MethodKeysOf<T>]: T[K] extends MockableFunction ? MockedFunctionDeep<T[K]> : T[K];
502 } & { [K in PropertyKeysOf<T>]: MaybeMockedDeep<T[K]> };
503 type MaybeMockedDeep<T> = T extends MockableFunction
504 ? MockedFunctionDeep<T>
505 : T extends object // eslint-disable-line @typescript-eslint/ban-types
506 ? MockedObjectDeep<T>
507 : T;
508 // eslint-disable-next-line @typescript-eslint/ban-types
509 type MaybeMocked<T> = T extends MockableFunction ? MockedFn<T> : T extends object ? MockedObject<T> : T;
510 type EmptyFunction = () => void;
511 type ArgsType<T> = T extends (...args: infer A) => any ? A : never;
512 type Constructor = new (...args: any[]) => any;
513 type Func = (...args: any[]) => any;
514 type ConstructorArgsType<T> = T extends new (...args: infer A) => any ? A : never;
515 type RejectedValue<T> = T extends PromiseLike<any> ? any : never;
516 type ResolvedValue<T> = T extends PromiseLike<infer U> ? U | T : never;
517 // see https://github.com/Microsoft/TypeScript/issues/25215
518 type NonFunctionPropertyNames<T> = keyof { [K in keyof T as T[K] extends Func ? never : K]: T[K] };
519 type GetAccessor = 'get';
520 type SetAccessor = 'set';
521 type PropertyAccessors<M extends keyof T, T extends {}> = M extends NonFunctionPropertyNames<Required<T>>
522 ? GetAccessor | SetAccessor
523 : never;
524 type FunctionProperties<T> = { [K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] };
525 type FunctionPropertyNames<T> = keyof FunctionProperties<T>;
526 type RemoveIndex<T> = {
527 // from https://stackoverflow.com/a/66252656/4536543
528 [P in keyof T as string extends P ? never : number extends P ? never : P]: T[P];
529 };
530 type ConstructorProperties<T> = {
531 [K in keyof RemoveIndex<T> as RemoveIndex<T>[K] extends Constructor ? K : never]: RemoveIndex<T>[K];
532 };
533 type ConstructorPropertyNames<T> = RemoveIndex<keyof ConstructorProperties<T>>;
534
535 interface DoneCallback {
536 (...args: any[]): any;
537 fail(error?: string | { message: string }): any;
538 }
539
540 type ProvidesCallback = ((cb: DoneCallback) => void | undefined) | (() => Promise<unknown>);
541 type ProvidesHookCallback = (() => any) | ProvidesCallback;
542
543 type Lifecycle = (fn: ProvidesHookCallback, timeout?: number) => any;
544
545 interface FunctionLike {
546 readonly name: string;
547 }
548
549 interface Each {
550 // Exclusively arrays.
551 <T extends any[] | [any]>(cases: ReadonlyArray<T>): (
552 name: string,
553 fn: (...args: T) => any,
554 timeout?: number,
555 ) => void;
556 <T extends ReadonlyArray<any>>(cases: ReadonlyArray<T>): (
557 name: string,
558 fn: (...args: ExtractEachCallbackArgs<T>) => any,
559 timeout?: number,
560 ) => void;
561 // Not arrays.
562 <T>(cases: ReadonlyArray<T>): (name: string, fn: (arg: T, done: DoneCallback) => any, timeout?: number) => void;
563 (cases: ReadonlyArray<ReadonlyArray<any>>): (
564 name: string,
565 fn: (...args: any[]) => any,
566 timeout?: number,
567 ) => void;
568 (strings: TemplateStringsArray, ...placeholders: any[]): (
569 name: string,
570 fn: (arg: any, done: DoneCallback) => any,
571 timeout?: number,
572 ) => void;
573 }
574
575 /**
576 * Creates a test closure
577 */
578 interface It {
579 /**
580 * Creates a test closure.
581 *
582 * @param name The name of your test
583 * @param fn The function for your test
584 * @param timeout The timeout for an async function test
585 */
586 (name: string, fn?: ProvidesCallback, timeout?: number): void;
587 /**
588 * Only runs this test in the current file.
589 */
590 only: It;
591 /**
592 * Mark this test as expecting to fail.
593 *
594 * Only available in the default `jest-circus` runner.
595 */
596 failing: It;
597 /**
598 * Skips running this test in the current file.
599 */
600 skip: It;
601 /**
602 * Sketch out which tests to write in the future.
603 */
604 todo: It;
605 /**
606 * Experimental and should be avoided.
607 */
608 concurrent: It;
609 /**
610 * Use if you keep duplicating the same test with different data. `.each` allows you to write the
611 * test once and pass data in.
612 *
613 * `.each` is available with two APIs:
614 *
615 * #### 1 `test.each(table)(name, fn)`
616 *
617 * - `table`: Array of Arrays with the arguments that are passed into the test fn for each row.
618 * - `name`: String the title of the test block.
619 * - `fn`: Function the test to be ran, this is the function that will receive the parameters in each row as function arguments.
620 *
621 *
622 * #### 2 `test.each table(name, fn)`
623 *
624 * - `table`: Tagged Template Literal
625 * - `name`: String the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions.
626 * - `fn`: Function the test to be ran, this is the function that will receive the test data object..
627 *
628 * @example
629 *
630 * // API 1
631 * test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])(
632 * '.add(%i, %i)',
633 * (a, b, expected) => {
634 * expect(a + b).toBe(expected);
635 * },
636 * );
637 *
638 * // API 2
639 * test.each`
640 * a | b | expected
641 * ${1} | ${1} | ${2}
642 * ${1} | ${2} | ${3}
643 * ${2} | ${1} | ${3}
644 * `('returns $expected when $a is added $b', ({a, b, expected}) => {
645 * expect(a + b).toBe(expected);
646 * });
647 *
648 */
649 each: Each;
650 }
651
652 interface Describe {
653 // tslint:disable-next-line ban-types
654 (name: number | string | Function | FunctionLike, fn: EmptyFunction): void;
655 /** Only runs the tests inside this `describe` for the current file */
656 only: Describe;
657 /** Skips running the tests inside this `describe` for the current file */
658 skip: Describe;
659 each: Each;
660 }
661
662 type EqualityTester = (a: any, b: any) => boolean | undefined;
663
664 type MatcherUtils = import('expect').MatcherUtils & { [other: string]: any };
665
666 interface ExpectExtendMap {
667 [key: string]: CustomMatcher;
668 }
669
670 type MatcherContext = MatcherUtils & Readonly<MatcherState>;
671 type CustomMatcher = (
672 this: MatcherContext,
673 received: any,
674 ...actual: any[]
675 ) => CustomMatcherResult | Promise<CustomMatcherResult>;
676
677 interface CustomMatcherResult {
678 pass: boolean;
679 message: () => string;
680 }
681
682 type SnapshotSerializerPlugin = import('pretty-format').Plugin;
683
684 interface InverseAsymmetricMatchers {
685 /**
686 * `expect.not.arrayContaining(array)` matches a received array which
687 * does not contain all of the elements in the expected array. That is,
688 * the expected array is not a subset of the received array. It is the
689 * inverse of `expect.arrayContaining`.
690 *
691 * Optionally, you can provide a type for the elements via a generic.
692 */
693 // eslint-disable-next-line no-unnecessary-generics
694 arrayContaining<E = any>(arr: readonly E[]): any;
695 /**
696 * `expect.not.objectContaining(object)` matches any received object
697 * that does not recursively match the expected properties. That is, the
698 * expected object is not a subset of the received object. Therefore,
699 * it matches a received object which contains properties that are not
700 * in the expected object. It is the inverse of `expect.objectContaining`.
701 *
702 * Optionally, you can provide a type for the object via a generic.
703 * This ensures that the object contains the desired structure.
704 */
705 // eslint-disable-next-line no-unnecessary-generics
706 objectContaining<E = {}>(obj: E): any;
707 /**
708 * `expect.not.stringMatching(string | regexp)` matches the received
709 * string that does not match the expected regexp. It is the inverse of
710 * `expect.stringMatching`.
711 */
712 stringMatching(str: string | RegExp): any;
713 /**
714 * `expect.not.stringContaining(string)` matches the received string
715 * that does not contain the exact expected string. It is the inverse of
716 * `expect.stringContaining`.
717 */
718 stringContaining(str: string): any;
719 }
720 type MatcherState = import('expect').MatcherState;
721 /**
722 * The `expect` function is used every time you want to test a value.
723 * You will rarely call `expect` by itself.
724 */
725 interface Expect {
726 /**
727 * The `expect` function is used every time you want to test a value.
728 * You will rarely call `expect` by itself.
729 *
730 * @param actual The value to apply matchers against.
731 */
732 <T = any>(actual: T): JestMatchers<T>;
733 /**
734 * Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead
735 * of a literal value. For example, if you want to check that a mock function is called with a
736 * non-null argument:
737 *
738 * @example
739 *
740 * test('map calls its argument with a non-null argument', () => {
741 * const mock = jest.fn();
742 * [1].map(x => mock(x));
743 * expect(mock).toBeCalledWith(expect.anything());
744 * });
745 *
746 */
747 anything(): any;
748 /**
749 * Matches anything that was created with the given constructor.
750 * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
751 *
752 * @example
753 *
754 * function randocall(fn) {
755 * return fn(Math.floor(Math.random() * 6 + 1));
756 * }
757 *
758 * test('randocall calls its callback with a number', () => {
759 * const mock = jest.fn();
760 * randocall(mock);
761 * expect(mock).toBeCalledWith(expect.any(Number));
762 * });
763 */
764 any(classType: any): any;
765 /**
766 * Matches any array made up entirely of elements in the provided array.
767 * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
768 *
769 * Optionally, you can provide a type for the elements via a generic.
770 */
771 // eslint-disable-next-line no-unnecessary-generics
772 arrayContaining<E = any>(arr: readonly E[]): any;
773 /**
774 * Verifies that a certain number of assertions are called during a test.
775 * This is often useful when testing asynchronous code, in order to
776 * make sure that assertions in a callback actually got called.
777 */
778 assertions(num: number): void;
779 /**
780 * Useful when comparing floating point numbers in object properties or array item.
781 * If you need to compare a number, use `.toBeCloseTo` instead.
782 *
783 * The optional `numDigits` argument limits the number of digits to check after the decimal point.
784 * For the default value 2, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`).
785 */
786 closeTo(num: number, numDigits?: number): any;
787 /**
788 * Verifies that at least one assertion is called during a test.
789 * This is often useful when testing asynchronous code, in order to
790 * make sure that assertions in a callback actually got called.
791 */
792 hasAssertions(): void;
793 /**
794 * You can use `expect.extend` to add your own matchers to Jest.
795 */
796 extend(obj: ExpectExtendMap): void;
797 /**
798 * Adds a module to format application-specific data structures for serialization.
799 */
800 addSnapshotSerializer(serializer: SnapshotSerializerPlugin): void;
801 /**
802 * Matches any object that recursively matches the provided keys.
803 * This is often handy in conjunction with other asymmetric matchers.
804 *
805 * Optionally, you can provide a type for the object via a generic.
806 * This ensures that the object contains the desired structure.
807 */
808 // eslint-disable-next-line no-unnecessary-generics
809 objectContaining<E = {}>(obj: E): any;
810 /**
811 * Matches any string that contains the exact provided string
812 */
813 stringMatching(str: string | RegExp): any;
814 /**
815 * Matches any received string that contains the exact expected string
816 */
817 stringContaining(str: string): any;
818
819 not: InverseAsymmetricMatchers;
820
821 setState(state: object): void;
822 getState(): MatcherState & Record<string, any>;
823 }
824
825 type JestMatchers<T> = JestMatchersShape<Matchers<void, T>, Matchers<Promise<void>, T>>;
826
827 type JestMatchersShape<TNonPromise extends {} = {}, TPromise extends {} = {}> = {
828 /**
829 * Use resolves to unwrap the value of a fulfilled promise so any other
830 * matcher can be chained. If the promise is rejected the assertion fails.
831 */
832 resolves: AndNot<TPromise>;
833 /**
834 * Unwraps the reason of a rejected promise so any other matcher can be chained.
835 * If the promise is fulfilled the assertion fails.
836 */
837 rejects: AndNot<TPromise>;
838 } & AndNot<TNonPromise>;
839 type AndNot<T> = T & {
840 not: T;
841 };
842
843 // should be R extends void|Promise<void> but getting dtslint error
844 interface Matchers<R, T = {}> {
845 /**
846 * Ensures the last call to a mock function was provided specific args.
847 *
848 * Optionally, you can provide a type for the expected arguments via a generic.
849 * Note that the type must be either an array or a tuple.
850 */
851 // eslint-disable-next-line no-unnecessary-generics
852 lastCalledWith<E extends any[]>(...args: E): R;
853 /**
854 * Ensure that the last call to a mock function has returned a specified value.
855 *
856 * Optionally, you can provide a type for the expected value via a generic.
857 * This is particularly useful for ensuring expected objects have the right structure.
858 */
859 // eslint-disable-next-line no-unnecessary-generics
860 lastReturnedWith<E = any>(expected?: E): R;
861 /**
862 * Ensure that a mock function is called with specific arguments on an Nth call.
863 *
864 * Optionally, you can provide a type for the expected arguments via a generic.
865 * Note that the type must be either an array or a tuple.
866 */
867 // eslint-disable-next-line no-unnecessary-generics
868 nthCalledWith<E extends any[]>(nthCall: number, ...params: E): R;
869 /**
870 * Ensure that the nth call to a mock function has returned a specified value.
871 *
872 * Optionally, you can provide a type for the expected value via a generic.
873 * This is particularly useful for ensuring expected objects have the right structure.
874 */
875 // eslint-disable-next-line no-unnecessary-generics
876 nthReturnedWith<E = any>(n: number, expected?: E): R;
877 /**
878 * Checks that a value is what you expect. It uses `Object.is` to check strict equality.
879 * Don't use `toBe` with floating-point numbers.
880 *
881 * Optionally, you can provide a type for the expected value via a generic.
882 * This is particularly useful for ensuring expected objects have the right structure.
883 */
884 // eslint-disable-next-line no-unnecessary-generics
885 toBe<E = any>(expected: E): R;
886 /**
887 * Ensures that a mock function is called.
888 */
889 toBeCalled(): R;
890 /**
891 * Ensures that a mock function is called an exact number of times.
892 */
893 toBeCalledTimes(expected: number): R;
894 /**
895 * Ensure that a mock function is called with specific arguments.
896 *
897 * Optionally, you can provide a type for the expected arguments via a generic.
898 * Note that the type must be either an array or a tuple.
899 */
900 // eslint-disable-next-line no-unnecessary-generics
901 toBeCalledWith<E extends any[]>(...args: E): R;
902 /**
903 * Using exact equality with floating point numbers is a bad idea.
904 * Rounding means that intuitive things fail.
905 * The default for numDigits is 2.
906 */
907 toBeCloseTo(expected: number, numDigits?: number): R;
908 /**
909 * Ensure that a variable is not undefined.
910 */
911 toBeDefined(): R;
912 /**
913 * When you don't care what a value is, you just want to
914 * ensure a value is false in a boolean context.
915 */
916 toBeFalsy(): R;
917 /**
918 * For comparing floating point or big integer numbers.
919 */
920 toBeGreaterThan(expected: number | bigint): R;
921 /**
922 * For comparing floating point or big integer numbers.
923 */
924 toBeGreaterThanOrEqual(expected: number | bigint): R;
925 /**
926 * Ensure that an object is an instance of a class.
927 * This matcher uses `instanceof` underneath.
928 *
929 * Optionally, you can provide a type for the expected value via a generic.
930 * This is particularly useful for ensuring expected objects have the right structure.
931 */
932 // eslint-disable-next-line no-unnecessary-generics
933 toBeInstanceOf<E = any>(expected: E): R;
934 /**
935 * For comparing floating point or big integer numbers.
936 */
937 toBeLessThan(expected: number | bigint): R;
938 /**
939 * For comparing floating point or big integer numbers.
940 */
941 toBeLessThanOrEqual(expected: number | bigint): R;
942 /**
943 * This is the same as `.toBe(null)` but the error messages are a bit nicer.
944 * So use `.toBeNull()` when you want to check that something is null.
945 */
946 toBeNull(): R;
947 /**
948 * Use when you don't care what a value is, you just want to ensure a value
949 * is true in a boolean context. In JavaScript, there are six falsy values:
950 * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
951 */
952 toBeTruthy(): R;
953 /**
954 * Used to check that a variable is undefined.
955 */
956 toBeUndefined(): R;
957 /**
958 * Used to check that a variable is NaN.
959 */
960 toBeNaN(): R;
961 /**
962 * Used when you want to check that an item is in a list.
963 * For testing the items in the list, this uses `===`, a strict equality check.
964 * It can also check whether a string is a substring of another string.
965 *
966 * Optionally, you can provide a type for the expected value via a generic.
967 * This is particularly useful for ensuring expected objects have the right structure.
968 */
969 // eslint-disable-next-line no-unnecessary-generics
970 toContain<E = any>(expected: E): R;
971 /**
972 * Used when you want to check that an item is in a list.
973 * For testing the items in the list, this matcher recursively checks the
974 * equality of all fields, rather than checking for object identity.
975 *
976 * Optionally, you can provide a type for the expected value via a generic.
977 * This is particularly useful for ensuring expected objects have the right structure.
978 */
979 // eslint-disable-next-line no-unnecessary-generics
980 toContainEqual<E = any>(expected: E): R;
981 /**
982 * Used when you want to check that two objects have the same value.
983 * This matcher recursively checks the equality of all fields, rather than checking for object identity.
984 *
985 * Optionally, you can provide a type for the expected value via a generic.
986 * This is particularly useful for ensuring expected objects have the right structure.
987 */
988 // eslint-disable-next-line no-unnecessary-generics
989 toEqual<E = any>(expected: E): R;
990 /**
991 * Ensures that a mock function is called.
992 */
993 toHaveBeenCalled(): R;
994 /**
995 * Ensures that a mock function is called an exact number of times.
996 */
997 toHaveBeenCalledTimes(expected: number): R;
998 /**
999 * Ensure that a mock function is called with specific arguments.
1000 *
1001 * Optionally, you can provide a type for the expected arguments via a generic.
1002 * Note that the type must be either an array or a tuple.
1003 */
1004 // eslint-disable-next-line no-unnecessary-generics
1005 toHaveBeenCalledWith<E extends any[]>(...params: E): R;
1006 /**
1007 * Ensure that a mock function is called with specific arguments on an Nth call.
1008 *
1009 * Optionally, you can provide a type for the expected arguments via a generic.
1010 * Note that the type must be either an array or a tuple.
1011 */
1012 // eslint-disable-next-line no-unnecessary-generics
1013 toHaveBeenNthCalledWith<E extends any[]>(nthCall: number, ...params: E): R;
1014 /**
1015 * If you have a mock function, you can use `.toHaveBeenLastCalledWith`
1016 * to test what arguments it was last called with.
1017 *
1018 * Optionally, you can provide a type for the expected arguments via a generic.
1019 * Note that the type must be either an array or a tuple.
1020 */
1021 // eslint-disable-next-line no-unnecessary-generics
1022 toHaveBeenLastCalledWith<E extends any[]>(...params: E): R;
1023 /**
1024 * Use to test the specific value that a mock function last returned.
1025 * If the last call to the mock function threw an error, then this matcher will fail
1026 * no matter what value you provided as the expected return value.
1027 *
1028 * Optionally, you can provide a type for the expected value via a generic.
1029 * This is particularly useful for ensuring expected objects have the right structure.
1030 */
1031 // eslint-disable-next-line no-unnecessary-generics
1032 toHaveLastReturnedWith<E = any>(expected?: E): R;
1033 /**
1034 * Used to check that an object has a `.length` property
1035 * and it is set to a certain numeric value.
1036 */
1037 toHaveLength(expected: number): R;
1038 /**
1039 * Use to test the specific value that a mock function returned for the nth call.
1040 * If the nth call to the mock function threw an error, then this matcher will fail
1041 * no matter what value you provided as the expected return value.
1042 *
1043 * Optionally, you can provide a type for the expected value via a generic.
1044 * This is particularly useful for ensuring expected objects have the right structure.
1045 */
1046 // eslint-disable-next-line no-unnecessary-generics
1047 toHaveNthReturnedWith<E = any>(nthCall: number, expected?: E): R;
1048 /**
1049 * Use to check if property at provided reference keyPath exists for an object.
1050 * For checking deeply nested properties in an object you may use dot notation or an array containing
1051 * the keyPath for deep references.
1052 *
1053 * Optionally, you can provide a value to check if it's equal to the value present at keyPath
1054 * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
1055 * the equality of all fields.
1056 *
1057 * @example
1058 *
1059 * expect(houseForSale).toHaveProperty('kitchen.area', 20);
1060 */
1061 // eslint-disable-next-line no-unnecessary-generics
1062 toHaveProperty<E = any>(propertyPath: string | readonly any[], value?: E): R;
1063 /**
1064 * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
1065 */
1066 toHaveReturned(): R;
1067 /**
1068 * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
1069 * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
1070 */
1071 toHaveReturnedTimes(expected: number): R;
1072 /**
1073 * Use to ensure that a mock function returned a specific value.
1074 *
1075 * Optionally, you can provide a type for the expected value via a generic.
1076 * This is particularly useful for ensuring expected objects have the right structure.
1077 */
1078 // eslint-disable-next-line no-unnecessary-generics
1079 toHaveReturnedWith<E = any>(expected?: E): R;
1080 /**
1081 * Check that a string matches a regular expression.
1082 */
1083 toMatch(expected: string | RegExp): R;
1084 /**
1085 * Used to check that a JavaScript object matches a subset of the properties of an object
1086 *
1087 * Optionally, you can provide an object to use as Generic type for the expected value.
1088 * This ensures that the matching object matches the structure of the provided object-like type.
1089 *
1090 * @example
1091 *
1092 * type House = {
1093 * bath: boolean;
1094 * bedrooms: number;
1095 * kitchen: {
1096 * amenities: string[];
1097 * area: number;
1098 * wallColor: string;
1099 * }
1100 * };
1101 *
1102 * expect(desiredHouse).toMatchObject<House>({...standardHouse, kitchen: {area: 20}}) // wherein standardHouse is some base object of type House
1103 */
1104 // eslint-disable-next-line no-unnecessary-generics
1105 toMatchObject<E extends {} | any[]>(expected: E): R;
1106 /**
1107 * This ensures that a value matches the most recent snapshot with property matchers.
1108 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1109 */
1110 // eslint-disable-next-line no-unnecessary-generics
1111 toMatchSnapshot<U extends { [P in keyof T]: any }>(propertyMatchers: Partial<U>, snapshotName?: string): R;
1112 /**
1113 * This ensures that a value matches the most recent snapshot.
1114 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1115 */
1116 toMatchSnapshot(snapshotName?: string): R;
1117 /**
1118 * This ensures that a value matches the most recent snapshot with property matchers.
1119 * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
1120 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1121 */
1122 // eslint-disable-next-line no-unnecessary-generics
1123 toMatchInlineSnapshot<U extends { [P in keyof T]: any }>(propertyMatchers: Partial<U>, snapshot?: string): R;
1124 /**
1125 * This ensures that a value matches the most recent snapshot with property matchers.
1126 * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
1127 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1128 */
1129 toMatchInlineSnapshot(snapshot?: string): R;
1130 /**
1131 * Ensure that a mock function has returned (as opposed to thrown) at least once.
1132 */
1133 toReturn(): R;
1134 /**
1135 * Ensure that a mock function has returned (as opposed to thrown) a specified number of times.
1136 */
1137 toReturnTimes(count: number): R;
1138 /**
1139 * Ensure that a mock function has returned a specified value at least once.
1140 *
1141 * Optionally, you can provide a type for the expected value via a generic.
1142 * This is particularly useful for ensuring expected objects have the right structure.
1143 */
1144 // eslint-disable-next-line no-unnecessary-generics
1145 toReturnWith<E = any>(value?: E): R;
1146 /**
1147 * Use to test that objects have the same types as well as structure.
1148 *
1149 * Optionally, you can provide a type for the expected value via a generic.
1150 * This is particularly useful for ensuring expected objects have the right structure.
1151 */
1152 // eslint-disable-next-line no-unnecessary-generics
1153 toStrictEqual<E = any>(expected: E): R;
1154 /**
1155 * Used to test that a function throws when it is called.
1156 */
1157 toThrow(error?: string | Constructable | RegExp | Error): R;
1158 /**
1159 * If you want to test that a specific error is thrown inside a function.
1160 */
1161 toThrowError(error?: string | Constructable | RegExp | Error): R;
1162 /**
1163 * Used to test that a function throws a error matching the most recent snapshot when it is called.
1164 */
1165 toThrowErrorMatchingSnapshot(snapshotName?: string): R;
1166 /**
1167 * Used to test that a function throws a error matching the most recent snapshot when it is called.
1168 * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
1169 */
1170 toThrowErrorMatchingInlineSnapshot(snapshot?: string): R;
1171 }
1172
1173 type RemoveFirstFromTuple<T extends any[]> = T['length'] extends 0
1174 ? []
1175 : ((...b: T) => void) extends (a: any, ...b: infer I) => void
1176 ? I
1177 : [];
1178
1179 interface AsymmetricMatcher {
1180 asymmetricMatch(other: unknown): boolean;
1181 }
1182 type NonAsyncMatchers<TMatchers extends ExpectExtendMap> = {
1183 [K in keyof TMatchers]: ReturnType<TMatchers[K]> extends Promise<CustomMatcherResult> ? never : K;
1184 }[keyof TMatchers];
1185 type CustomAsyncMatchers<TMatchers extends ExpectExtendMap> = {
1186 [K in NonAsyncMatchers<TMatchers>]: CustomAsymmetricMatcher<TMatchers[K]>;
1187 };
1188 type CustomAsymmetricMatcher<TMatcher extends (...args: any[]) => any> = (
1189 ...args: RemoveFirstFromTuple<Parameters<TMatcher>>
1190 ) => AsymmetricMatcher;
1191
1192 // should be TMatcherReturn extends void|Promise<void> but getting dtslint error
1193 type CustomJestMatcher<TMatcher extends (...args: any[]) => any, TMatcherReturn> = (
1194 ...args: RemoveFirstFromTuple<Parameters<TMatcher>>
1195 ) => TMatcherReturn;
1196
1197 type ExpectProperties = {
1198 [K in keyof Expect]: Expect[K];
1199 };
1200 // should be TMatcherReturn extends void|Promise<void> but getting dtslint error
1201 // Use the `void` type for return types only. Otherwise, use `undefined`. See: https://github.com/Microsoft/dtslint/blob/master/docs/void-return.md
1202 // have added issue https://github.com/microsoft/dtslint/issues/256 - Cannot have type union containing void ( to be used as return type only
1203 type ExtendedMatchers<TMatchers extends ExpectExtendMap, TMatcherReturn, TActual> = Matchers<
1204 TMatcherReturn,
1205 TActual
1206 > & { [K in keyof TMatchers]: CustomJestMatcher<TMatchers[K], TMatcherReturn> };
1207 type JestExtendedMatchers<TMatchers extends ExpectExtendMap, TActual> = JestMatchersShape<
1208 ExtendedMatchers<TMatchers, void, TActual>,
1209 ExtendedMatchers<TMatchers, Promise<void>, TActual>
1210 >;
1211
1212 // when have called expect.extend
1213 type ExtendedExpectFunction<TMatchers extends ExpectExtendMap> = <TActual>(
1214 actual: TActual,
1215 ) => JestExtendedMatchers<TMatchers, TActual>;
1216
1217 type ExtendedExpect<TMatchers extends ExpectExtendMap> = ExpectProperties &
1218 AndNot<CustomAsyncMatchers<TMatchers>> &
1219 ExtendedExpectFunction<TMatchers>;
1220
1221 type NonPromiseMatchers<T extends JestMatchersShape<any>> = Omit<T, 'resolves' | 'rejects' | 'not'>;
1222 type PromiseMatchers<T extends JestMatchersShape> = Omit<T['resolves'], 'not'>;
1223
1224 interface Constructable {
1225 new (...args: any[]): any;
1226 }
1227
1228 interface Mock<T = any, Y extends any[] = any, C = any> extends Function, MockInstance<T, Y, C> {
1229 new (...args: Y): T;
1230 (this: C, ...args: Y): T;
1231 }
1232
1233 interface SpyInstance<T = any, Y extends any[] = any, C = any> extends MockInstance<T, Y, C> {}
1234
1235 /**
1236 * Constructs the type of a spied class.
1237 */
1238 type SpiedClass<T extends abstract new (...args: any) => any> = SpyInstance<
1239 InstanceType<T>,
1240 ConstructorParameters<T>,
1241 T extends abstract new (...args: any) => infer C ? C : never
1242 >;
1243
1244 /**
1245 * Constructs the type of a spied function.
1246 */
1247 type SpiedFunction<T extends (...args: any) => any> = SpyInstance<
1248 ReturnType<T>,
1249 ArgsType<T>,
1250 T extends (this: infer C, ...args: any) => any ? C : never
1251 >;
1252
1253 /**
1254 * Constructs the type of a spied getter.
1255 */
1256 type SpiedGetter<T> = SpyInstance<T, []>;
1257
1258 /**
1259 * Constructs the type of a spied setter.
1260 */
1261 type SpiedSetter<T> = SpyInstance<void, [T]>;
1262
1263 /**
1264 * Constructs the type of a spied class or function.
1265 */
1266 type Spied<T extends (abstract new (...args: any) => any) | ((...args: any) => any)> = T extends abstract new (
1267 ...args: any
1268 ) => any
1269 ? SpiedClass<T>
1270 : T extends (...args: any) => any
1271 ? SpiedFunction<T>
1272 : never;
1273
1274 /**
1275 * Wrap a function with mock definitions
1276 *
1277 * @example
1278 *
1279 * import { myFunction } from "./library";
1280 * jest.mock("./library");
1281 *
1282 * const mockMyFunction = myFunction as jest.MockedFunction<typeof myFunction>;
1283 * expect(mockMyFunction.mock.calls[0][0]).toBe(42);
1284 */
1285 type MockedFunction<T extends (...args: any[]) => any> = MockInstance<
1286 ReturnType<T>,
1287 ArgsType<T>,
1288 T extends (this: infer C, ...args: any[]) => any ? C : never
1289 > &
1290 T;
1291
1292 /**
1293 * Wrap a class with mock definitions
1294 *
1295 * @example
1296 *
1297 * import { MyClass } from "./library";
1298 * jest.mock("./library");
1299 *
1300 * const mockedMyClass = MyClass as jest.MockedClass<typeof MyClass>;
1301 *
1302 * expect(mockedMyClass.mock.calls[0][0]).toBe(42); // Constructor calls
1303 * expect(mockedMyClass.prototype.myMethod.mock.calls[0][0]).toBe(42); // Method calls
1304 */
1305
1306 type MockedClass<T extends Constructable> = MockInstance<
1307 InstanceType<T>,
1308 T extends new (...args: infer P) => any ? P : never,
1309 T extends new (...args: any[]) => infer C ? C : never
1310 > & {
1311 prototype: T extends { prototype: any } ? Mocked<T['prototype']> : never;
1312 } & T;
1313
1314 /**
1315 * Wrap an object or a module with mock definitions
1316 *
1317 * @example
1318 *
1319 * jest.mock("../api");
1320 * import * as api from "../api";
1321 *
1322 * const mockApi = api as jest.Mocked<typeof api>;
1323 * api.MyApi.prototype.myApiMethod.mockImplementation(() => "test");
1324 */
1325 type Mocked<T> = {
1326 [P in keyof T]: T[P] extends (this: infer C, ...args: any[]) => any
1327 ? MockInstance<ReturnType<T[P]>, ArgsType<T[P]>, C>
1328 : T[P] extends Constructable
1329 ? MockedClass<T[P]>
1330 : T[P];
1331 } & T;
1332
1333 interface MockInstance<T, Y extends any[], C = any> {
1334 /** Returns the mock name string set by calling `mockFn.mockName(value)`. */
1335 getMockName(): string;
1336 /** Provides access to the mock's metadata */
1337 mock: MockContext<T, Y, C>;
1338 /**
1339 * Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays.
1340 *
1341 * Often this is useful when you want to clean up a mock's usage data between two assertions.
1342 *
1343 * Beware that `mockClear` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`.
1344 * You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you
1345 * don't access stale data.
1346 */
1347 mockClear(): this;
1348 /**
1349 * Resets all information stored in the mock, including any initial implementation and mock name given.
1350 *
1351 * This is useful when you want to completely restore a mock back to its initial state.
1352 *
1353 * Beware that `mockReset` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`.
1354 * You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you
1355 * don't access stale data.
1356 */
1357 mockReset(): this;
1358 /**
1359 * Does everything that `mockFn.mockReset()` does, and also restores the original (non-mocked) implementation.
1360 *
1361 * This is useful when you want to mock functions in certain test cases and restore the original implementation in others.
1362 *
1363 * Beware that `mockFn.mockRestore` only works when mock was created with `jest.spyOn`. Thus you have to take care of restoration
1364 * yourself when manually assigning `jest.fn()`.
1365 *
1366 * The [`restoreMocks`](https://jestjs.io/docs/en/configuration.html#restoremocks-boolean) configuration option is available
1367 * to restore mocks automatically between tests.
1368 */
1369 mockRestore(): void;
1370 /**
1371 * Returns the function that was set as the implementation of the mock (using mockImplementation).
1372 */
1373 getMockImplementation(): ((...args: Y) => T) | undefined;
1374 /**
1375 * Accepts a function that should be used as the implementation of the mock. The mock itself will still record
1376 * all calls that go into and instances that come from itselfthe only difference is that the implementation
1377 * will also be executed when the mock is called.
1378 *
1379 * Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`.
1380 */
1381 mockImplementation(fn?: (...args: Y) => T): this;
1382 /**
1383 * Accepts a function that will be used as an implementation of the mock for one call to the mocked function.
1384 * Can be chained so that multiple function calls produce different results.
1385 *
1386 * @example
1387 *
1388 * const myMockFn = jest
1389 * .fn()
1390 * .mockImplementationOnce(cb => cb(null, true))
1391 * .mockImplementationOnce(cb => cb(null, false));
1392 *
1393 * myMockFn((err, val) => console.log(val)); // true
1394 *
1395 * myMockFn((err, val) => console.log(val)); // false
1396 */
1397 mockImplementationOnce(fn: (...args: Y) => T): this;
1398 /**
1399 * Temporarily overrides the default mock implementation within the callback,
1400 * then restores its previous implementation.
1401 *
1402 * @remarks
1403 * If the callback is async or returns a `thenable`, `withImplementation` will return a promise.
1404 * Awaiting the promise will await the callback and reset the implementation.
1405 */
1406 withImplementation(fn: (...args: Y) => T, callback: () => Promise<unknown>): Promise<void>;
1407 /**
1408 * Temporarily overrides the default mock implementation within the callback,
1409 * then restores its previous implementation.
1410 */
1411 withImplementation(fn: (...args: Y) => T, callback: () => void): void;
1412 /** Sets the name of the mock. */
1413 mockName(name: string): this;
1414 /**
1415 * Just a simple sugar function for:
1416 *
1417 * @example
1418 *
1419 * jest.fn(function() {
1420 * return this;
1421 * });
1422 */
1423 mockReturnThis(): this;
1424 /**
1425 * Accepts a value that will be returned whenever the mock function is called.
1426 *
1427 * @example
1428 *
1429 * const mock = jest.fn();
1430 * mock.mockReturnValue(42);
1431 * mock(); // 42
1432 * mock.mockReturnValue(43);
1433 * mock(); // 43
1434 */
1435 mockReturnValue(value: T): this;
1436 /**
1437 * Accepts a value that will be returned for one call to the mock function. Can be chained so that
1438 * successive calls to the mock function return different values. When there are no more
1439 * `mockReturnValueOnce` values to use, calls will return a value specified by `mockReturnValue`.
1440 *
1441 * @example
1442 *
1443 * const myMockFn = jest.fn()
1444 * .mockReturnValue('default')
1445 * .mockReturnValueOnce('first call')
1446 * .mockReturnValueOnce('second call');
1447 *
1448 * // 'first call', 'second call', 'default', 'default'
1449 * console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
1450 *
1451 */
1452 mockReturnValueOnce(value: T): this;
1453 /**
1454 * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.resolve(value));`
1455 */
1456 mockResolvedValue(value: ResolvedValue<T>): this;
1457 /**
1458 * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.resolve(value));`
1459 *
1460 * @example
1461 *
1462 * test('async test', async () => {
1463 * const asyncMock = jest
1464 * .fn()
1465 * .mockResolvedValue('default')
1466 * .mockResolvedValueOnce('first call')
1467 * .mockResolvedValueOnce('second call');
1468 *
1469 * await asyncMock(); // first call
1470 * await asyncMock(); // second call
1471 * await asyncMock(); // default
1472 * await asyncMock(); // default
1473 * });
1474 *
1475 */
1476 mockResolvedValueOnce(value: ResolvedValue<T>): this;
1477 /**
1478 * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.reject(value));`
1479 *
1480 * @example
1481 *
1482 * test('async test', async () => {
1483 * const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
1484 *
1485 * await asyncMock(); // throws "Async error"
1486 * });
1487 */
1488 mockRejectedValue(value: RejectedValue<T>): this;
1489
1490 /**
1491 * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.reject(value));`
1492 *
1493 * @example
1494 *
1495 * test('async test', async () => {
1496 * const asyncMock = jest
1497 * .fn()
1498 * .mockResolvedValueOnce('first call')
1499 * .mockRejectedValueOnce(new Error('Async error'));
1500 *
1501 * await asyncMock(); // first call
1502 * await asyncMock(); // throws "Async error"
1503 * });
1504 *
1505 */
1506 mockRejectedValueOnce(value: RejectedValue<T>): this;
1507 }
1508
1509 /**
1510 * Represents the result of a single call to a mock function with a return value.
1511 */
1512 interface MockResultReturn<T> {
1513 type: 'return';
1514 value: T;
1515 }
1516 /**
1517 * Represents the result of a single incomplete call to a mock function.
1518 */
1519 interface MockResultIncomplete {
1520 type: 'incomplete';
1521 value: undefined;
1522 }
1523 /**
1524 * Represents the result of a single call to a mock function with a thrown error.
1525 */
1526 interface MockResultThrow {
1527 type: 'throw';
1528 value: any;
1529 }
1530
1531 type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
1532
1533 interface MockContext<T, Y extends any[], C = any> {
1534 /**
1535 * List of the call arguments of all calls that have been made to the mock.
1536 */
1537 calls: Y[];
1538 /**
1539 * List of the call contexts of all calls that have been made to the mock.
1540 */
1541 contexts: C[];
1542 /**
1543 * List of all the object instances that have been instantiated from the mock.
1544 */
1545 instances: T[];
1546 /**
1547 * List of the call order indexes of the mock. Jest is indexing the order of
1548 * invocations of all mocks in a test file. The index is starting with `1`.
1549 */
1550 invocationCallOrder: number[];
1551 /**
1552 * List of the call arguments of the last call that was made to the mock.
1553 * If the function was not called, it will return `undefined`.
1554 */
1555 lastCall?: Y;
1556 /**
1557 * List of the results of all calls that have been made to the mock.
1558 */
1559 results: Array<MockResult<T>>;
1560 }
1561
1562 interface ReplaceProperty<K> {
1563 /**
1564 * Restore property to its original value known at the time of mocking.
1565 */
1566 restore(): void;
1567 /**
1568 * Change the value of the property.
1569 */
1570 replaceValue(value: K): this;
1571 }
1572}
1573
1574// Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected.
1575// Relevant parts of Jasmine's API are below so they can be changed and removed over time.
1576// This file can't reference jasmine.d.ts since the globals aren't compatible.
1577
1578declare function spyOn<T>(object: T, method: keyof T): jasmine.Spy;
1579/**
1580 * If you call the function pending anywhere in the spec body,
1581 * no matter the expectations, the spec will be marked pending.
1582 */
1583declare function pending(reason?: string): void;
1584/**
1585 * Fails a test when called within one.
1586 */
1587declare function fail(error?: any): never;
1588declare namespace jasmine {
1589 let DEFAULT_TIMEOUT_INTERVAL: number;
1590 function clock(): Clock;
1591 function any(aclass: any): Any;
1592 function anything(): Any;
1593 function arrayContaining(sample: readonly any[]): ArrayContaining;
1594 function objectContaining(sample: any): ObjectContaining;
1595 function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy;
1596 function createSpyObj(baseName: string, methodNames: any[]): any;
1597 // eslint-disable-next-line no-unnecessary-generics
1598 function createSpyObj<T>(baseName: string, methodNames: any[]): T;
1599 function pp(value: any): string;
1600 function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
1601 function stringMatching(value: string | RegExp): Any;
1602
1603 interface Clock {
1604 install(): void;
1605 uninstall(): void;
1606 /**
1607 * Calls to any registered callback are triggered when the clock isticked forward
1608 * via the jasmine.clock().tick function, which takes a number of milliseconds.
1609 */
1610 tick(ms: number): void;
1611 mockDate(date?: Date): void;
1612 }
1613
1614 interface Any {
1615 new (expectedClass: any): any;
1616 jasmineMatches(other: any): boolean;
1617 jasmineToString(): string;
1618 }
1619
1620 interface ArrayContaining {
1621 new (sample: readonly any[]): any;
1622 asymmetricMatch(other: any): boolean;
1623 jasmineToString(): string;
1624 }
1625
1626 interface ObjectContaining {
1627 new (sample: any): any;
1628 jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;
1629 jasmineToString(): string;
1630 }
1631
1632 interface Spy {
1633 (...params: any[]): any;
1634 identity: string;
1635 and: SpyAnd;
1636 calls: Calls;
1637 mostRecentCall: { args: any[] };
1638 argsForCall: any[];
1639 wasCalled: boolean;
1640 }
1641
1642 interface SpyAnd {
1643 /**
1644 * By chaining the spy with and.callThrough, the spy will still track all
1645 * calls to it but in addition it will delegate to the actual implementation.
1646 */
1647 callThrough(): Spy;
1648 /**
1649 * By chaining the spy with and.returnValue, all calls to the function
1650 * will return a specific value.
1651 */
1652 returnValue(val: any): Spy;
1653 /**
1654 * By chaining the spy with and.returnValues, all calls to the function
1655 * will return specific values in order until it reaches the end of the return values list.
1656 */
1657 returnValues(...values: any[]): Spy;
1658 /**
1659 * By chaining the spy with and.callFake, all calls to the spy
1660 * will delegate to the supplied function.
1661 */
1662 callFake(fn: (...args: any[]) => any): Spy;
1663 /**
1664 * By chaining the spy with and.throwError, all calls to the spy
1665 * will throw the specified value.
1666 */
1667 throwError(msg: string): Spy;
1668 /**
1669 * When a calling strategy is used for a spy, the original stubbing
1670 * behavior can be returned at any time with and.stub.
1671 */
1672 stub(): Spy;
1673 }
1674
1675 interface Calls {
1676 /**
1677 * By chaining the spy with calls.any(),
1678 * will return false if the spy has not been called at all,
1679 * and then true once at least one call happens.
1680 */
1681 any(): boolean;
1682 /**
1683 * By chaining the spy with calls.count(),
1684 * will return the number of times the spy was called
1685 */
1686 count(): number;
1687 /**
1688 * By chaining the spy with calls.argsFor(),
1689 * will return the arguments passed to call number index
1690 */
1691 argsFor(index: number): any[];
1692 /**
1693 * By chaining the spy with calls.allArgs(),
1694 * will return the arguments to all calls
1695 */
1696 allArgs(): any[];
1697 /**
1698 * By chaining the spy with calls.all(), will return the
1699 * context (the this) and arguments passed all calls
1700 */
1701 all(): CallInfo[];
1702 /**
1703 * By chaining the spy with calls.mostRecent(), will return the
1704 * context (the this) and arguments for the most recent call
1705 */
1706 mostRecent(): CallInfo;
1707 /**
1708 * By chaining the spy with calls.first(), will return the
1709 * context (the this) and arguments for the first call
1710 */
1711 first(): CallInfo;
1712 /**
1713 * By chaining the spy with calls.reset(), will clears all tracking for a spy
1714 */
1715 reset(): void;
1716 }
1717
1718 interface CallInfo {
1719 /**
1720 * The context (the this) for the call
1721 */
1722 object: any;
1723 /**
1724 * All arguments passed to the call
1725 */
1726 args: any[];
1727 /**
1728 * The return value of the call
1729 */
1730 returnValue: any;
1731 }
1732
1733 interface CustomMatcherFactories {
1734 [index: string]: CustomMatcherFactory;
1735 }
1736
1737 type CustomMatcherFactory = (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => CustomMatcher;
1738
1739 interface MatchersUtil {
1740 equals(a: any, b: any, customTesters?: CustomEqualityTester[]): boolean;
1741 // eslint-disable-next-line no-unnecessary-generics
1742 contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: CustomEqualityTester[]): boolean;
1743 buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string;
1744 }
1745
1746 type CustomEqualityTester = (first: any, second: any) => boolean;
1747
1748 interface CustomMatcher {
1749 compare<T>(actual: T, expected: T, ...args: any[]): CustomMatcherResult;
1750 compare(actual: any, ...expected: any[]): CustomMatcherResult;
1751 }
1752
1753 interface CustomMatcherResult {
1754 pass: boolean;
1755 message: string | (() => string);
1756 }
1757
1758 interface ArrayLike<T> {
1759 length: number;
1760 [n: number]: T;
1761 }
1762}
1763
1764interface ImportMeta {
1765 jest: typeof jest;
1766}
1767
\No newline at end of file