UNPKG

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