UNPKG

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