UNPKG

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