UNPKG

71.1 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 | undefined;
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 // eslint-disable-line @typescript-eslint/ban-types
467 ? MockedObjectDeep<T>
468 : T;
469 // eslint-disable-next-line @typescript-eslint/ban-types
470 type MaybeMocked<T> = T extends MockableFunction ? MockedFn<T> : T extends object ? MockedObject<T> : T;
471 type EmptyFunction = () => void;
472 type ArgsType<T> = T extends (...args: infer A) => any ? A : never;
473 type Constructor = new(...args: any[]) => any;
474 type Func = (...args: any[]) => any;
475 type ConstructorArgsType<T> = T extends new(...args: infer A) => any ? A : never;
476 type RejectedValue<T> = T extends PromiseLike<any> ? any : never;
477 type ResolvedValue<T> = T extends PromiseLike<infer U> ? U | T : never;
478 // see https://github.com/Microsoft/TypeScript/issues/25215
479 type NonFunctionPropertyNames<T> = keyof { [K in keyof T as T[K] extends Func ? never : K]: T[K] };
480 type GetAccessor = "get";
481 type SetAccessor = "set";
482 type PropertyAccessors<M extends keyof T, T extends {}> = M extends NonFunctionPropertyNames<Required<T>>
483 ? GetAccessor | SetAccessor
484 : never;
485 type FunctionProperties<T> = { [K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K] };
486 type FunctionPropertyNames<T> = keyof FunctionProperties<T>;
487 type RemoveIndex<T> = {
488 // from https://stackoverflow.com/a/66252656/4536543
489 [P in keyof T as string extends P ? never : number extends P ? never : P]: T[P];
490 };
491 type ConstructorProperties<T> = {
492 [K in keyof RemoveIndex<T> as RemoveIndex<T>[K] extends Constructor ? K : never]: RemoveIndex<T>[K];
493 };
494 type ConstructorPropertyNames<T> = RemoveIndex<keyof ConstructorProperties<T>>;
495
496 interface DoneCallback {
497 (...args: any[]): any;
498 fail(error?: string | { message: string }): any;
499 }
500
501 // eslint-disable-next-line @typescript-eslint/no-invalid-void-type
502 type ProvidesCallback = ((cb: DoneCallback) => void | undefined) | (() => PromiseLike<unknown>);
503 type ProvidesHookCallback = (() => any) | ProvidesCallback;
504
505 type Lifecycle = (fn: ProvidesHookCallback, timeout?: number) => any;
506
507 interface FunctionLike {
508 readonly name: string;
509 }
510
511 interface Each {
512 // Exclusively arrays.
513 <T extends any[] | [any]>(cases: readonly T[]): (
514 name: string,
515 fn: (...args: T) => any,
516 timeout?: number,
517 ) => void;
518 <T extends readonly any[]>(cases: readonly T[]): (
519 name: string,
520 fn: (...args: ExtractEachCallbackArgs<T>) => any,
521 timeout?: number,
522 ) => void;
523 // Not arrays.
524 <T>(cases: readonly T[]): (name: string, fn: (arg: T, done: DoneCallback) => any, timeout?: number) => void;
525 (cases: ReadonlyArray<readonly any[]>): (
526 name: string,
527 fn: (...args: any[]) => any,
528 timeout?: number,
529 ) => void;
530 (strings: TemplateStringsArray, ...placeholders: any[]): (
531 name: string,
532 fn: (arg: any, done: DoneCallback) => any,
533 timeout?: number,
534 ) => void;
535 }
536
537 /**
538 * Creates a test closure
539 */
540 interface It {
541 /**
542 * Creates a test closure.
543 *
544 * @param name The name of your test
545 * @param fn The function for your test
546 * @param timeout The timeout for an async function test
547 */
548 (name: string, fn?: ProvidesCallback, timeout?: number): void;
549 /**
550 * Only runs this test in the current file.
551 */
552 only: It;
553 /**
554 * Mark this test as expecting to fail.
555 *
556 * Only available in the default `jest-circus` runner.
557 */
558 failing: It;
559 /**
560 * Skips running this test in the current file.
561 */
562 skip: It;
563 /**
564 * Sketch out which tests to write in the future.
565 */
566 todo: (name: string) => void;
567 /**
568 * Experimental and should be avoided.
569 */
570 concurrent: It;
571 /**
572 * Use if you keep duplicating the same test with different data. `.each` allows you to write the
573 * test once and pass data in.
574 *
575 * `.each` is available with two APIs:
576 *
577 * #### 1 `test.each(table)(name, fn)`
578 *
579 * - `table`: Array of Arrays with the arguments that are passed into the test fn for each row.
580 * - `name`: String the title of the test block.
581 * - `fn`: Function the test to be run, this is the function that will receive the parameters in each row as function arguments.
582 *
583 * #### 2 `test.each table(name, fn)`
584 *
585 * - `table`: Tagged Template Literal
586 * - `name`: String the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions.
587 * - `fn`: Function the test to be run, this is the function that will receive the test data object.
588 *
589 * @example
590 *
591 * // API 1
592 * test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])(
593 * '.add(%i, %i)',
594 * (a, b, expected) => {
595 * expect(a + b).toBe(expected);
596 * },
597 * );
598 *
599 * // API 2
600 * test.each`
601 * a | b | expected
602 * ${1} | ${1} | ${2}
603 * ${1} | ${2} | ${3}
604 * ${2} | ${1} | ${3}
605 * `('returns $expected when $a is added $b', ({a, b, expected}) => {
606 * expect(a + b).toBe(expected);
607 * });
608 */
609 each: Each;
610 }
611
612 interface Describe {
613 // eslint-disable-next-line @typescript-eslint/ban-types
614 (name: number | string | Function | FunctionLike, fn: EmptyFunction): void;
615 /** Only runs the tests inside this `describe` for the current file */
616 only: Describe;
617 /** Skips running the tests inside this `describe` for the current file */
618 skip: Describe;
619 each: Each;
620 }
621
622 type EqualityTester = (a: any, b: any) => boolean | undefined;
623
624 type MatcherUtils = import("expect").MatcherUtils & { [other: string]: any };
625
626 interface ExpectExtendMap {
627 [key: string]: CustomMatcher;
628 }
629
630 type MatcherContext = MatcherUtils & Readonly<MatcherState>;
631 type CustomMatcher = (
632 this: MatcherContext,
633 received: any,
634 ...actual: any[]
635 ) => CustomMatcherResult | Promise<CustomMatcherResult>;
636
637 interface CustomMatcherResult {
638 pass: boolean;
639 message: () => string;
640 }
641
642 type SnapshotSerializerPlugin = import("pretty-format").Plugin;
643
644 interface InverseAsymmetricMatchers {
645 /**
646 * `expect.not.arrayContaining(array)` matches a received array which
647 * does not contain all of the elements in the expected array. That is,
648 * the expected array is not a subset of the received array. It is the
649 * inverse of `expect.arrayContaining`.
650 *
651 * Optionally, you can provide a type for the elements via a generic.
652 */
653 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
654 arrayContaining<E = any>(arr: readonly E[]): any;
655 /**
656 * `expect.not.objectContaining(object)` matches any received object
657 * that does not recursively match the expected properties. That is, the
658 * expected object is not a subset of the received object. Therefore,
659 * it matches a received object which contains properties that are not
660 * in the expected object. It is the inverse of `expect.objectContaining`.
661 *
662 * Optionally, you can provide a type for the object via a generic.
663 * This ensures that the object contains the desired structure.
664 */
665 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
666 objectContaining<E = {}>(obj: E): any;
667 /**
668 * `expect.not.stringMatching(string | regexp)` matches the received
669 * string that does not match the expected regexp. It is the inverse of
670 * `expect.stringMatching`.
671 */
672 stringMatching(str: string | RegExp): any;
673 /**
674 * `expect.not.stringContaining(string)` matches the received string
675 * that does not contain the exact expected string. It is the inverse of
676 * `expect.stringContaining`.
677 */
678 stringContaining(str: string): any;
679 }
680 type MatcherState = import("expect").MatcherState;
681 /**
682 * The `expect` function is used every time you want to test a value.
683 * You will rarely call `expect` by itself.
684 */
685 interface Expect {
686 /**
687 * The `expect` function is used every time you want to test a value.
688 * You will rarely call `expect` by itself.
689 *
690 * @param actual The value to apply matchers against.
691 */
692 <T = any>(actual: T): JestMatchers<T>;
693 /**
694 * Matches anything but null or undefined. You can use it inside `toEqual` or `toBeCalledWith` instead
695 * of a literal value. For example, if you want to check that a mock function is called with a
696 * non-null argument:
697 *
698 * @example
699 *
700 * test('map calls its argument with a non-null argument', () => {
701 * const mock = jest.fn();
702 * [1].map(x => mock(x));
703 * expect(mock).toBeCalledWith(expect.anything());
704 * });
705 */
706 anything(): any;
707 /**
708 * Matches anything that was created with the given constructor.
709 * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
710 *
711 * @example
712 *
713 * function randocall(fn) {
714 * return fn(Math.floor(Math.random() * 6 + 1));
715 * }
716 *
717 * test('randocall calls its callback with a number', () => {
718 * const mock = jest.fn();
719 * randocall(mock);
720 * expect(mock).toBeCalledWith(expect.any(Number));
721 * });
722 */
723 any(classType: any): any;
724 /**
725 * Matches any array made up entirely of elements in the provided array.
726 * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value.
727 *
728 * Optionally, you can provide a type for the elements via a generic.
729 */
730 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
731 arrayContaining<E = any>(arr: readonly E[]): any;
732 /**
733 * Verifies that a certain number of assertions are called during a test.
734 * This is often useful when testing asynchronous code, in order to
735 * make sure that assertions in a callback actually got called.
736 */
737 assertions(num: number): void;
738 /**
739 * Useful when comparing floating point numbers in object properties or array item.
740 * If you need to compare a number, use `.toBeCloseTo` instead.
741 *
742 * The optional `numDigits` argument limits the number of digits to check after the decimal point.
743 * For the default value 2, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`).
744 */
745 closeTo(num: number, numDigits?: number): any;
746 /**
747 * Verifies that at least one assertion is called during a test.
748 * This is often useful when testing asynchronous code, in order to
749 * make sure that assertions in a callback actually got called.
750 */
751 hasAssertions(): void;
752 /**
753 * You can use `expect.extend` to add your own matchers to Jest.
754 */
755 extend(obj: ExpectExtendMap): void;
756 /**
757 * Adds a module to format application-specific data structures for serialization.
758 */
759 addSnapshotSerializer(serializer: SnapshotSerializerPlugin): void;
760 /**
761 * Matches any object that recursively matches the provided keys.
762 * This is often handy in conjunction with other asymmetric matchers.
763 *
764 * Optionally, you can provide a type for the object via a generic.
765 * This ensures that the object contains the desired structure.
766 */
767 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
768 objectContaining<E = {}>(obj: E): any;
769 /**
770 * Matches any string that contains the exact provided string
771 */
772 stringMatching(str: string | RegExp): any;
773 /**
774 * Matches any received string that contains the exact expected string
775 */
776 stringContaining(str: string): any;
777
778 not: InverseAsymmetricMatchers;
779
780 setState(state: object): void;
781 getState(): MatcherState & Record<string, any>;
782 }
783
784 type JestMatchers<T> = JestMatchersShape<Matchers<void, T>, Matchers<Promise<void>, T>>;
785
786 type JestMatchersShape<TNonPromise extends {} = {}, TPromise extends {} = {}> = {
787 /**
788 * Use resolves to unwrap the value of a fulfilled promise so any other
789 * matcher can be chained. If the promise is rejected the assertion fails.
790 */
791 resolves: AndNot<TPromise>;
792 /**
793 * Unwraps the reason of a rejected promise so any other matcher can be chained.
794 * If the promise is fulfilled the assertion fails.
795 */
796 rejects: AndNot<TPromise>;
797 } & AndNot<TNonPromise>;
798 type AndNot<T> = T & {
799 not: T;
800 };
801
802 // should be R extends void|Promise<void> but getting dtslint error
803 interface Matchers<R, T = {}> {
804 /**
805 * Ensures the last call to a mock function was provided specific args.
806 *
807 * Optionally, you can provide a type for the expected arguments via a generic.
808 * Note that the type must be either an array or a tuple.
809 *
810 * @deprecated in favor of `toHaveBeenLastCalledWith`
811 */
812 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
813 lastCalledWith<E extends any[]>(...args: E): R;
814 /**
815 * Ensure that the last call to a mock function has returned a specified value.
816 *
817 * Optionally, you can provide a type for the expected value via a generic.
818 * This is particularly useful for ensuring expected objects have the right structure.
819 *
820 * @deprecated in favor of `toHaveLastReturnedWith`
821 */
822 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
823 lastReturnedWith<E = any>(expected?: E): R;
824 /**
825 * Ensure that a mock function is called with specific arguments on an Nth call.
826 *
827 * Optionally, you can provide a type for the expected arguments via a generic.
828 * Note that the type must be either an array or a tuple.
829 *
830 * @deprecated in favor of `toHaveBeenNthCalledWith`
831 */
832 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
833 nthCalledWith<E extends any[]>(nthCall: number, ...params: E): R;
834 /**
835 * Ensure that the nth call to a mock function has returned a specified value.
836 *
837 * Optionally, you can provide a type for the expected value via a generic.
838 * This is particularly useful for ensuring expected objects have the right structure.
839 *
840 * @deprecated in favor of `toHaveNthReturnedWith`
841 */
842 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
843 nthReturnedWith<E = any>(n: number, expected?: E): R;
844 /**
845 * Checks that a value is what you expect. It uses `Object.is` to check strict equality.
846 * Don't use `toBe` with floating-point numbers.
847 *
848 * Optionally, you can provide a type for the expected value via a generic.
849 * This is particularly useful for ensuring expected objects have the right structure.
850 */
851 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
852 toBe<E = any>(expected: E): R;
853 /**
854 * Ensures that a mock function is called.
855 *
856 * @deprecated in favor of `toHaveBeenCalled`
857 */
858 toBeCalled(): R;
859 /**
860 * Ensures that a mock function is called an exact number of times.
861 *
862 * @deprecated in favor of `toHaveBeenCalledTimes`
863 */
864 toBeCalledTimes(expected: number): R;
865 /**
866 * Ensure that a mock function is called with specific arguments.
867 *
868 * Optionally, you can provide a type for the expected arguments via a generic.
869 * Note that the type must be either an array or a tuple.
870 *
871 * @deprecated in favor of `toHaveBeenCalledWith`
872 */
873 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
874 toBeCalledWith<E extends any[]>(...args: E): R;
875 /**
876 * Using exact equality with floating point numbers is a bad idea.
877 * Rounding means that intuitive things fail.
878 * The default for numDigits is 2.
879 */
880 toBeCloseTo(expected: number, numDigits?: number): R;
881 /**
882 * Ensure that a variable is not undefined.
883 */
884 toBeDefined(): R;
885 /**
886 * When you don't care what a value is, you just want to
887 * ensure a value is false in a boolean context.
888 */
889 toBeFalsy(): R;
890 /**
891 * For comparing floating point or big integer numbers.
892 */
893 toBeGreaterThan(expected: number | bigint): R;
894 /**
895 * For comparing floating point or big integer numbers.
896 */
897 toBeGreaterThanOrEqual(expected: number | bigint): R;
898 /**
899 * Ensure that an object is an instance of a class.
900 * This matcher uses `instanceof` underneath.
901 *
902 * Optionally, you can provide a type for the expected value via a generic.
903 * This is particularly useful for ensuring expected objects have the right structure.
904 */
905 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
906 toBeInstanceOf<E = any>(expected: E): R;
907 /**
908 * For comparing floating point or big integer numbers.
909 */
910 toBeLessThan(expected: number | bigint): R;
911 /**
912 * For comparing floating point or big integer numbers.
913 */
914 toBeLessThanOrEqual(expected: number | bigint): R;
915 /**
916 * This is the same as `.toBe(null)` but the error messages are a bit nicer.
917 * So use `.toBeNull()` when you want to check that something is null.
918 */
919 toBeNull(): R;
920 /**
921 * Use when you don't care what a value is, you just want to ensure a value
922 * is true in a boolean context. In JavaScript, there are six falsy values:
923 * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy.
924 */
925 toBeTruthy(): R;
926 /**
927 * Used to check that a variable is undefined.
928 */
929 toBeUndefined(): R;
930 /**
931 * Used to check that a variable is NaN.
932 */
933 toBeNaN(): R;
934 /**
935 * Used when you want to check that an item is in a list.
936 * For testing the items in the list, this uses `===`, a strict equality check.
937 * It can also check whether a string is a substring of another string.
938 *
939 * Optionally, you can provide a type for the expected value via a generic.
940 * This is particularly useful for ensuring expected objects have the right structure.
941 */
942 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
943 toContain<E = any>(expected: E): R;
944 /**
945 * Used when you want to check that an item is in a list.
946 * For testing the items in the list, this matcher recursively checks the
947 * equality of all fields, rather than checking for object identity.
948 *
949 * Optionally, you can provide a type for the expected value via a generic.
950 * This is particularly useful for ensuring expected objects have the right structure.
951 */
952 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
953 toContainEqual<E = any>(expected: E): R;
954 /**
955 * Used when you want to check that two objects have the same value.
956 * This matcher recursively checks the equality of all fields, rather than checking for object identity.
957 *
958 * Optionally, you can provide a type for the expected value via a generic.
959 * This is particularly useful for ensuring expected objects have the right structure.
960 */
961 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
962 toEqual<E = any>(expected: E): R;
963 /**
964 * Ensures that a mock function is called.
965 */
966 toHaveBeenCalled(): R;
967 /**
968 * Ensures that a mock function is called an exact number of times.
969 */
970 toHaveBeenCalledTimes(expected: number): R;
971 /**
972 * Ensure that a mock function is called with specific arguments.
973 *
974 * Optionally, you can provide a type for the expected arguments via a generic.
975 * Note that the type must be either an array or a tuple.
976 */
977 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
978 toHaveBeenCalledWith<E extends any[]>(...params: E): R;
979 /**
980 * Ensure that a mock function is called with specific arguments on an Nth call.
981 *
982 * Optionally, you can provide a type for the expected arguments via a generic.
983 * Note that the type must be either an array or a tuple.
984 */
985 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
986 toHaveBeenNthCalledWith<E extends any[]>(nthCall: number, ...params: E): R;
987 /**
988 * If you have a mock function, you can use `.toHaveBeenLastCalledWith`
989 * to test what arguments it was last called with.
990 *
991 * Optionally, you can provide a type for the expected arguments via a generic.
992 * Note that the type must be either an array or a tuple.
993 */
994 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
995 toHaveBeenLastCalledWith<E extends any[]>(...params: E): R;
996 /**
997 * Use to test the specific value that a mock function last returned.
998 * If the last call to the mock function threw an error, then this matcher will fail
999 * no matter what value you provided as the expected return value.
1000 *
1001 * Optionally, you can provide a type for the expected value via a generic.
1002 * This is particularly useful for ensuring expected objects have the right structure.
1003 */
1004 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1005 toHaveLastReturnedWith<E = any>(expected?: E): R;
1006 /**
1007 * Used to check that an object has a `.length` property
1008 * and it is set to a certain numeric value.
1009 */
1010 toHaveLength(expected: number): R;
1011 /**
1012 * Use to test the specific value that a mock function returned for the nth call.
1013 * If the nth call to the mock function threw an error, then this matcher will fail
1014 * no matter what value you provided as the expected return value.
1015 *
1016 * Optionally, you can provide a type for the expected value via a generic.
1017 * This is particularly useful for ensuring expected objects have the right structure.
1018 */
1019 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1020 toHaveNthReturnedWith<E = any>(nthCall: number, expected?: E): R;
1021 /**
1022 * Use to check if property at provided reference keyPath exists for an object.
1023 * For checking deeply nested properties in an object you may use dot notation or an array containing
1024 * the keyPath for deep references.
1025 *
1026 * Optionally, you can provide a value to check if it's equal to the value present at keyPath
1027 * on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks
1028 * the equality of all fields.
1029 *
1030 * @example
1031 *
1032 * expect(houseForSale).toHaveProperty('kitchen.area', 20);
1033 */
1034 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1035 toHaveProperty<E = any>(propertyPath: string | readonly any[], value?: E): R;
1036 /**
1037 * Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
1038 */
1039 toHaveReturned(): R;
1040 /**
1041 * Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times.
1042 * Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
1043 */
1044 toHaveReturnedTimes(expected: number): R;
1045 /**
1046 * Use to ensure that a mock function returned a specific value.
1047 *
1048 * Optionally, you can provide a type for the expected value via a generic.
1049 * This is particularly useful for ensuring expected objects have the right structure.
1050 */
1051 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1052 toHaveReturnedWith<E = any>(expected?: E): R;
1053 /**
1054 * Check that a string matches a regular expression.
1055 */
1056 toMatch(expected: string | RegExp): R;
1057 /**
1058 * Used to check that a JavaScript object matches a subset of the properties of an object
1059 *
1060 * Optionally, you can provide an object to use as Generic type for the expected value.
1061 * This ensures that the matching object matches the structure of the provided object-like type.
1062 *
1063 * @example
1064 *
1065 * type House = {
1066 * bath: boolean;
1067 * bedrooms: number;
1068 * kitchen: {
1069 * amenities: string[];
1070 * area: number;
1071 * wallColor: string;
1072 * }
1073 * };
1074 *
1075 * expect(desiredHouse).toMatchObject<House>({...standardHouse, kitchen: {area: 20}}) // wherein standardHouse is some base object of type House
1076 */
1077 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1078 toMatchObject<E extends {} | any[]>(expected: E): R;
1079 /**
1080 * This ensures that a value matches the most recent snapshot with property matchers.
1081 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1082 */
1083 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1084 toMatchSnapshot<U extends { [P in keyof T]: any }>(propertyMatchers: Partial<U>, snapshotName?: string): R;
1085 /**
1086 * This ensures that a value matches the most recent snapshot.
1087 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1088 */
1089 toMatchSnapshot(snapshotName?: string): R;
1090 /**
1091 * This ensures that a value matches the most recent snapshot with property matchers.
1092 * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
1093 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1094 */
1095 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1096 toMatchInlineSnapshot<U extends { [P in keyof T]: any }>(propertyMatchers: Partial<U>, snapshot?: string): R;
1097 /**
1098 * This ensures that a value matches the most recent snapshot with property matchers.
1099 * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
1100 * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
1101 */
1102 toMatchInlineSnapshot(snapshot?: string): R;
1103 /**
1104 * Ensure that a mock function has returned (as opposed to thrown) at least once.
1105 *
1106 * @deprecated in favor of `toHaveReturned`
1107 */
1108 toReturn(): R;
1109 /**
1110 * Ensure that a mock function has returned (as opposed to thrown) a specified number of times.
1111 *
1112 * @deprecated in favor of `toHaveReturnedTimes`
1113 */
1114 toReturnTimes(count: number): R;
1115 /**
1116 * Ensure that a mock function has returned a specified value at least once.
1117 *
1118 * Optionally, you can provide a type for the expected value via a generic.
1119 * This is particularly useful for ensuring expected objects have the right structure.
1120 *
1121 * @deprecated in favor of `toHaveReturnedWith`
1122 */
1123 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1124 toReturnWith<E = any>(value?: E): R;
1125 /**
1126 * Use to test that objects have the same types as well as structure.
1127 *
1128 * Optionally, you can provide a type for the expected value via a generic.
1129 * This is particularly useful for ensuring expected objects have the right structure.
1130 */
1131 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1132 toStrictEqual<E = any>(expected: E): R;
1133 /**
1134 * Used to test that a function throws when it is called.
1135 */
1136 toThrow(error?: string | Constructable | RegExp | Error): R;
1137 /**
1138 * If you want to test that a specific error is thrown inside a function.
1139 *
1140 * @deprecated in favor of `toThrow`
1141 */
1142 toThrowError(error?: string | Constructable | RegExp | Error): R;
1143 /**
1144 * Used to test that a function throws a error matching the most recent snapshot when it is called.
1145 */
1146 toThrowErrorMatchingSnapshot(snapshotName?: string): R;
1147 /**
1148 * Used to test that a function throws a error matching the most recent snapshot when it is called.
1149 * Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
1150 */
1151 toThrowErrorMatchingInlineSnapshot(snapshot?: string): R;
1152 }
1153
1154 type RemoveFirstFromTuple<T extends any[]> = T["length"] extends 0 ? []
1155 : ((...b: T) => void) extends (a: any, ...b: infer I) => void ? I
1156 : [];
1157
1158 interface AsymmetricMatcher {
1159 asymmetricMatch(other: unknown): boolean;
1160 }
1161 type NonAsyncMatchers<TMatchers extends ExpectExtendMap> = {
1162 [K in keyof TMatchers]: ReturnType<TMatchers[K]> extends Promise<CustomMatcherResult> ? never : K;
1163 }[keyof TMatchers];
1164 type CustomAsyncMatchers<TMatchers extends ExpectExtendMap> = {
1165 [K in NonAsyncMatchers<TMatchers>]: CustomAsymmetricMatcher<TMatchers[K]>;
1166 };
1167 type CustomAsymmetricMatcher<TMatcher extends (...args: any[]) => any> = (
1168 ...args: RemoveFirstFromTuple<Parameters<TMatcher>>
1169 ) => AsymmetricMatcher;
1170
1171 // should be TMatcherReturn extends void|Promise<void> but getting dtslint error
1172 type CustomJestMatcher<TMatcher extends (...args: any[]) => any, TMatcherReturn> = (
1173 ...args: RemoveFirstFromTuple<Parameters<TMatcher>>
1174 ) => TMatcherReturn;
1175
1176 type ExpectProperties = {
1177 [K in keyof Expect]: Expect[K];
1178 };
1179 // should be TMatcherReturn extends void|Promise<void> but getting dtslint error
1180 // Use the `void` type for return types only. Otherwise, use `undefined`. See: https://github.com/Microsoft/dtslint/blob/master/docs/void-return.md
1181 // have added issue https://github.com/microsoft/dtslint/issues/256 - Cannot have type union containing void ( to be used as return type only
1182 type ExtendedMatchers<TMatchers extends ExpectExtendMap, TMatcherReturn, TActual> =
1183 & Matchers<
1184 TMatcherReturn,
1185 TActual
1186 >
1187 & { [K in keyof TMatchers]: CustomJestMatcher<TMatchers[K], TMatcherReturn> };
1188 type JestExtendedMatchers<TMatchers extends ExpectExtendMap, TActual> = JestMatchersShape<
1189 ExtendedMatchers<TMatchers, void, TActual>,
1190 ExtendedMatchers<TMatchers, Promise<void>, TActual>
1191 >;
1192
1193 // when have called expect.extend
1194 type ExtendedExpectFunction<TMatchers extends ExpectExtendMap> = <TActual>(
1195 actual: TActual,
1196 ) => JestExtendedMatchers<TMatchers, TActual>;
1197
1198 type ExtendedExpect<TMatchers extends ExpectExtendMap> =
1199 & ExpectProperties
1200 & AndNot<CustomAsyncMatchers<TMatchers>>
1201 & ExtendedExpectFunction<TMatchers>;
1202
1203 type NonPromiseMatchers<T extends JestMatchersShape<any>> = Omit<T, "resolves" | "rejects" | "not">;
1204 type PromiseMatchers<T extends JestMatchersShape> = Omit<T["resolves"], "not">;
1205
1206 interface Constructable {
1207 new(...args: any[]): any;
1208 }
1209
1210 interface Mock<T = any, Y extends any[] = any, C = any> extends Function, MockInstance<T, Y, C> {
1211 new(...args: Y): T;
1212 (this: C, ...args: Y): T;
1213 }
1214
1215 interface SpyInstance<T = any, Y extends any[] = any, C = any> extends MockInstance<T, Y, C> {}
1216
1217 /**
1218 * Constructs the type of a spied class.
1219 */
1220 type SpiedClass<T extends abstract new(...args: any) => any> = SpyInstance<
1221 InstanceType<T>,
1222 ConstructorParameters<T>,
1223 T extends abstract new(...args: any) => infer C ? C : never
1224 >;
1225
1226 /**
1227 * Constructs the type of a spied function.
1228 */
1229 type SpiedFunction<T extends (...args: any) => any> = SpyInstance<
1230 ReturnType<T>,
1231 ArgsType<T>,
1232 T extends (this: infer C, ...args: any) => any ? C : never
1233 >;
1234
1235 /**
1236 * Constructs the type of a spied getter.
1237 */
1238 type SpiedGetter<T> = SpyInstance<T, []>;
1239
1240 /**
1241 * Constructs the type of a spied setter.
1242 */
1243 type SpiedSetter<T> = SpyInstance<void, [T]>;
1244
1245 /**
1246 * Constructs the type of a spied class or function.
1247 */
1248 type Spied<T extends (abstract new(...args: any) => any) | ((...args: any) => any)> = T extends abstract new(
1249 ...args: any
1250 ) => any ? SpiedClass<T>
1251 : T extends (...args: any) => any ? SpiedFunction<T>
1252 : never;
1253
1254 /**
1255 * Wrap a function with mock definitions
1256 *
1257 * @example
1258 *
1259 * import { myFunction } from "./library";
1260 * jest.mock("./library");
1261 *
1262 * const mockMyFunction = myFunction as jest.MockedFunction<typeof myFunction>;
1263 * expect(mockMyFunction.mock.calls[0][0]).toBe(42);
1264 */
1265 type MockedFunction<T extends (...args: any[]) => any> =
1266 & MockInstance<
1267 ReturnType<T>,
1268 ArgsType<T>,
1269 T extends (this: infer C, ...args: any[]) => any ? C : never
1270 >
1271 & T;
1272
1273 /**
1274 * Wrap a class with mock definitions
1275 *
1276 * @example
1277 *
1278 * import { MyClass } from "./library";
1279 * jest.mock("./library");
1280 *
1281 * const mockedMyClass = MyClass as jest.MockedClass<typeof MyClass>;
1282 *
1283 * expect(mockedMyClass.mock.calls[0][0]).toBe(42); // Constructor calls
1284 * expect(mockedMyClass.prototype.myMethod.mock.calls[0][0]).toBe(42); // Method calls
1285 */
1286
1287 type MockedClass<T extends Constructable> =
1288 & MockInstance<
1289 InstanceType<T>,
1290 T extends new(...args: infer P) => any ? P : never,
1291 T extends new(...args: any[]) => infer C ? C : never
1292 >
1293 & {
1294 prototype: T extends { prototype: any } ? Mocked<T["prototype"]> : never;
1295 }
1296 & T;
1297
1298 /**
1299 * Wrap an object or a module with mock definitions
1300 *
1301 * @example
1302 *
1303 * jest.mock("../api");
1304 * import * as api from "../api";
1305 *
1306 * const mockApi = api as jest.Mocked<typeof api>;
1307 * api.MyApi.prototype.myApiMethod.mockImplementation(() => "test");
1308 */
1309 type Mocked<T> =
1310 & {
1311 [P in keyof T]: T[P] extends (this: infer C, ...args: any[]) => any
1312 ? MockInstance<ReturnType<T[P]>, ArgsType<T[P]>, C>
1313 : T[P] extends Constructable ? MockedClass<T[P]>
1314 : T[P];
1315 }
1316 & T;
1317
1318 interface MockInstance<T, Y extends any[], C = any> {
1319 /** Returns the mock name string set by calling `mockFn.mockName(value)`. */
1320 getMockName(): string;
1321 /** Provides access to the mock's metadata */
1322 mock: MockContext<T, Y, C>;
1323 /**
1324 * Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays.
1325 *
1326 * Often this is useful when you want to clean up a mock's usage data between two assertions.
1327 *
1328 * Beware that `mockClear` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`.
1329 * You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you
1330 * don't access stale data.
1331 */
1332 mockClear(): this;
1333 /**
1334 * Resets all information stored in the mock, including any initial implementation and mock name given.
1335 *
1336 * This is useful when you want to completely restore a mock back to its initial state.
1337 *
1338 * Beware that `mockReset` will replace `mockFn.mock`, not just `mockFn.mock.calls` and `mockFn.mock.instances`.
1339 * You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you
1340 * don't access stale data.
1341 */
1342 mockReset(): this;
1343 /**
1344 * Does everything that `mockFn.mockReset()` does, and also restores the original (non-mocked) implementation.
1345 *
1346 * This is useful when you want to mock functions in certain test cases and restore the original implementation in others.
1347 *
1348 * Beware that `mockFn.mockRestore` only works when mock was created with `jest.spyOn`. Thus you have to take care of restoration
1349 * yourself when manually assigning `jest.fn()`.
1350 *
1351 * The [`restoreMocks`](https://jestjs.io/docs/en/configuration.html#restoremocks-boolean) configuration option is available
1352 * to restore mocks automatically between tests.
1353 */
1354 mockRestore(): void;
1355 /**
1356 * Returns the function that was set as the implementation of the mock (using mockImplementation).
1357 */
1358 getMockImplementation(): ((...args: Y) => T) | undefined;
1359 /**
1360 * Accepts a function that should be used as the implementation of the mock. The mock itself will still record
1361 * all calls that go into and instances that come from itselfthe only difference is that the implementation
1362 * will also be executed when the mock is called.
1363 *
1364 * Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`.
1365 */
1366 mockImplementation(fn?: (...args: Y) => T): this;
1367 /**
1368 * Accepts a function that will be used as an implementation of the mock for one call to the mocked function.
1369 * Can be chained so that multiple function calls produce different results.
1370 *
1371 * @example
1372 *
1373 * const myMockFn = jest
1374 * .fn()
1375 * .mockImplementationOnce(cb => cb(null, true))
1376 * .mockImplementationOnce(cb => cb(null, false));
1377 *
1378 * myMockFn((err, val) => console.log(val)); // true
1379 *
1380 * myMockFn((err, val) => console.log(val)); // false
1381 */
1382 mockImplementationOnce(fn: (...args: Y) => T): this;
1383 /**
1384 * Temporarily overrides the default mock implementation within the callback,
1385 * then restores its previous implementation.
1386 *
1387 * @remarks
1388 * If the callback is async or returns a `thenable`, `withImplementation` will return a promise.
1389 * Awaiting the promise will await the callback and reset the implementation.
1390 */
1391 withImplementation(fn: (...args: Y) => T, callback: () => Promise<unknown>): Promise<void>;
1392 /**
1393 * Temporarily overrides the default mock implementation within the callback,
1394 * then restores its previous implementation.
1395 */
1396 withImplementation(fn: (...args: Y) => T, callback: () => void): void;
1397 /** Sets the name of the mock. */
1398 mockName(name: string): this;
1399 /**
1400 * Just a simple sugar function for:
1401 *
1402 * @example
1403 *
1404 * jest.fn(function() {
1405 * return this;
1406 * });
1407 */
1408 mockReturnThis(): this;
1409 /**
1410 * Accepts a value that will be returned whenever the mock function is called.
1411 *
1412 * @example
1413 *
1414 * const mock = jest.fn();
1415 * mock.mockReturnValue(42);
1416 * mock(); // 42
1417 * mock.mockReturnValue(43);
1418 * mock(); // 43
1419 */
1420 mockReturnValue(value: T): this;
1421 /**
1422 * Accepts a value that will be returned for one call to the mock function. Can be chained so that
1423 * successive calls to the mock function return different values. When there are no more
1424 * `mockReturnValueOnce` values to use, calls will return a value specified by `mockReturnValue`.
1425 *
1426 * @example
1427 *
1428 * const myMockFn = jest.fn()
1429 * .mockReturnValue('default')
1430 * .mockReturnValueOnce('first call')
1431 * .mockReturnValueOnce('second call');
1432 *
1433 * // 'first call', 'second call', 'default', 'default'
1434 * console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
1435 */
1436 mockReturnValueOnce(value: T): this;
1437 /**
1438 * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.resolve(value));`
1439 */
1440 mockResolvedValue(value: ResolvedValue<T>): this;
1441 /**
1442 * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.resolve(value));`
1443 *
1444 * @example
1445 *
1446 * test('async test', async () => {
1447 * const asyncMock = jest
1448 * .fn()
1449 * .mockResolvedValue('default')
1450 * .mockResolvedValueOnce('first call')
1451 * .mockResolvedValueOnce('second call');
1452 *
1453 * await asyncMock(); // first call
1454 * await asyncMock(); // second call
1455 * await asyncMock(); // default
1456 * await asyncMock(); // default
1457 * });
1458 */
1459 mockResolvedValueOnce(value: ResolvedValue<T>): this;
1460 /**
1461 * Simple sugar function for: `jest.fn().mockImplementation(() => Promise.reject(value));`
1462 *
1463 * @example
1464 *
1465 * test('async test', async () => {
1466 * const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
1467 *
1468 * await asyncMock(); // throws "Async error"
1469 * });
1470 */
1471 mockRejectedValue(value: RejectedValue<T>): this;
1472
1473 /**
1474 * Simple sugar function for: `jest.fn().mockImplementationOnce(() => Promise.reject(value));`
1475 *
1476 * @example
1477 *
1478 * test('async test', async () => {
1479 * const asyncMock = jest
1480 * .fn()
1481 * .mockResolvedValueOnce('first call')
1482 * .mockRejectedValueOnce(new Error('Async error'));
1483 *
1484 * await asyncMock(); // first call
1485 * await asyncMock(); // throws "Async error"
1486 * });
1487 */
1488 mockRejectedValueOnce(value: RejectedValue<T>): this;
1489 }
1490
1491 /**
1492 * Represents the result of a single call to a mock function with a return value.
1493 */
1494 interface MockResultReturn<T> {
1495 type: "return";
1496 value: T;
1497 }
1498 /**
1499 * Represents the result of a single incomplete call to a mock function.
1500 */
1501 interface MockResultIncomplete {
1502 type: "incomplete";
1503 value: undefined;
1504 }
1505 /**
1506 * Represents the result of a single call to a mock function with a thrown error.
1507 */
1508 interface MockResultThrow {
1509 type: "throw";
1510 value: any;
1511 }
1512
1513 type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
1514
1515 interface MockContext<T, Y extends any[], C = any> {
1516 /**
1517 * List of the call arguments of all calls that have been made to the mock.
1518 */
1519 calls: Y[];
1520 /**
1521 * List of the call contexts of all calls that have been made to the mock.
1522 */
1523 contexts: C[];
1524 /**
1525 * List of all the object instances that have been instantiated from the mock.
1526 */
1527 instances: T[];
1528 /**
1529 * List of the call order indexes of the mock. Jest is indexing the order of
1530 * invocations of all mocks in a test file. The index is starting with `1`.
1531 */
1532 invocationCallOrder: number[];
1533 /**
1534 * List of the call arguments of the last call that was made to the mock.
1535 * If the function was not called, it will return `undefined`.
1536 */
1537 lastCall?: Y;
1538 /**
1539 * List of the results of all calls that have been made to the mock.
1540 */
1541 results: Array<MockResult<T>>;
1542 }
1543
1544 interface ReplaceProperty<K> {
1545 /**
1546 * Restore property to its original value known at the time of mocking.
1547 */
1548 restore(): void;
1549 /**
1550 * Change the value of the property.
1551 */
1552 replaceValue(value: K): this;
1553 }
1554}
1555
1556// Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected.
1557// Relevant parts of Jasmine's API are below so they can be changed and removed over time.
1558// This file can't reference jasmine.d.ts since the globals aren't compatible.
1559
1560declare function spyOn<T>(object: T, method: keyof T): jasmine.Spy;
1561/**
1562 * If you call the function pending anywhere in the spec body,
1563 * no matter the expectations, the spec will be marked pending.
1564 */
1565declare function pending(reason?: string): void;
1566/**
1567 * Fails a test when called within one.
1568 */
1569declare function fail(error?: any): never;
1570declare namespace jasmine {
1571 let DEFAULT_TIMEOUT_INTERVAL: number;
1572 function clock(): Clock;
1573 function any(aclass: any): Any;
1574 function anything(): Any;
1575 function arrayContaining(sample: readonly any[]): ArrayContaining;
1576 function objectContaining(sample: any): ObjectContaining;
1577 function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy;
1578 function createSpyObj(baseName: string, methodNames: any[]): any;
1579 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1580 function createSpyObj<T>(baseName: string, methodNames: any[]): T;
1581 function pp(value: any): string;
1582 function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;
1583 function stringMatching(value: string | RegExp): Any;
1584
1585 interface Clock {
1586 install(): void;
1587 uninstall(): void;
1588 /**
1589 * Calls to any registered callback are triggered when the clock isticked forward
1590 * via the jasmine.clock().tick function, which takes a number of milliseconds.
1591 */
1592 tick(ms: number): void;
1593 mockDate(date?: Date): void;
1594 }
1595
1596 interface Any {
1597 new(expectedClass: any): any;
1598 jasmineMatches(other: any): boolean;
1599 jasmineToString(): string;
1600 }
1601
1602 interface ArrayContaining {
1603 new(sample: readonly any[]): any;
1604 asymmetricMatch(other: any): boolean;
1605 jasmineToString(): string;
1606 }
1607
1608 interface ObjectContaining {
1609 new(sample: any): any;
1610 jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;
1611 jasmineToString(): string;
1612 }
1613
1614 interface Spy {
1615 (...params: any[]): any;
1616 identity: string;
1617 and: SpyAnd;
1618 calls: Calls;
1619 mostRecentCall: { args: any[] };
1620 argsForCall: any[];
1621 wasCalled: boolean;
1622 }
1623
1624 interface SpyAnd {
1625 /**
1626 * By chaining the spy with and.callThrough, the spy will still track all
1627 * calls to it but in addition it will delegate to the actual implementation.
1628 */
1629 callThrough(): Spy;
1630 /**
1631 * By chaining the spy with and.returnValue, all calls to the function
1632 * will return a specific value.
1633 */
1634 returnValue(val: any): Spy;
1635 /**
1636 * By chaining the spy with and.returnValues, all calls to the function
1637 * will return specific values in order until it reaches the end of the return values list.
1638 */
1639 returnValues(...values: any[]): Spy;
1640 /**
1641 * By chaining the spy with and.callFake, all calls to the spy
1642 * will delegate to the supplied function.
1643 */
1644 callFake(fn: (...args: any[]) => any): Spy;
1645 /**
1646 * By chaining the spy with and.throwError, all calls to the spy
1647 * will throw the specified value.
1648 */
1649 throwError(msg: string): Spy;
1650 /**
1651 * When a calling strategy is used for a spy, the original stubbing
1652 * behavior can be returned at any time with and.stub.
1653 */
1654 stub(): Spy;
1655 }
1656
1657 interface Calls {
1658 /**
1659 * By chaining the spy with calls.any(),
1660 * will return false if the spy has not been called at all,
1661 * and then true once at least one call happens.
1662 */
1663 any(): boolean;
1664 /**
1665 * By chaining the spy with calls.count(),
1666 * will return the number of times the spy was called
1667 */
1668 count(): number;
1669 /**
1670 * By chaining the spy with calls.argsFor(),
1671 * will return the arguments passed to call number index
1672 */
1673 argsFor(index: number): any[];
1674 /**
1675 * By chaining the spy with calls.allArgs(),
1676 * will return the arguments to all calls
1677 */
1678 allArgs(): any[];
1679 /**
1680 * By chaining the spy with calls.all(), will return the
1681 * context (the this) and arguments passed all calls
1682 */
1683 all(): CallInfo[];
1684 /**
1685 * By chaining the spy with calls.mostRecent(), will return the
1686 * context (the this) and arguments for the most recent call
1687 */
1688 mostRecent(): CallInfo;
1689 /**
1690 * By chaining the spy with calls.first(), will return the
1691 * context (the this) and arguments for the first call
1692 */
1693 first(): CallInfo;
1694 /**
1695 * By chaining the spy with calls.reset(), will clears all tracking for a spy
1696 */
1697 reset(): void;
1698 }
1699
1700 interface CallInfo {
1701 /**
1702 * The context (the this) for the call
1703 */
1704 object: any;
1705 /**
1706 * All arguments passed to the call
1707 */
1708 args: any[];
1709 /**
1710 * The return value of the call
1711 */
1712 returnValue: any;
1713 }
1714
1715 interface CustomMatcherFactories {
1716 [index: string]: CustomMatcherFactory;
1717 }
1718
1719 type CustomMatcherFactory = (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => CustomMatcher;
1720
1721 interface MatchersUtil {
1722 equals(a: any, b: any, customTesters?: CustomEqualityTester[]): boolean;
1723 // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
1724 contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: CustomEqualityTester[]): boolean;
1725 buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string;
1726 }
1727
1728 type CustomEqualityTester = (first: any, second: any) => boolean;
1729
1730 interface CustomMatcher {
1731 compare<T>(actual: T, expected: T, ...args: any[]): CustomMatcherResult;
1732 compare(actual: any, ...expected: any[]): CustomMatcherResult;
1733 }
1734
1735 interface CustomMatcherResult {
1736 pass: boolean;
1737 message: string | (() => string);
1738 }
1739
1740 interface ArrayLike<T> {
1741 length: number;
1742 [n: number]: T;
1743 }
1744}
1745
1746interface ImportMeta {
1747 jest: typeof jest;
1748}
1749
\No newline at end of file