main
js 1,171 lines 33 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 'use strict';
11
12 /* eslint-disable no-unused-vars */
13
14 type JestMockFn<TArguments: $ReadOnlyArray<any>, TReturn> = {
15 (...args: TArguments): TReturn,
16 /**
17 * An object for introspecting mock calls
18 */
19 mock: {
20 /**
21 * An array that represents all calls that have been made into this mock
22 * function. Each call is represented by an array of arguments that were
23 * passed during the call.
24 */
25 calls: Array<TArguments>,
26 /**
27 * An array that contains all the object instances that have been
28 * instantiated from this mock function.
29 */
30 instances: Array<TReturn>,
31 /**
32 * An array that contains all the object results that have been
33 * returned by this mock function call
34 */
35 results: Array<{isThrow: boolean, value: TReturn}>,
36 },
37 /**
38 * Resets all information stored in the mockFn.mock.calls and
39 * mockFn.mock.instances arrays. Often this is useful when you want to clean
40 * up a mock's usage data between two assertions.
41 */
42 mockClear(): void,
43 /**
44 * Resets all information stored in the mock. This is useful when you want to
45 * completely restore a mock back to its initial state.
46 */
47 mockReset(): void,
48 /**
49 * Removes the mock and restores the initial implementation. This is useful
50 * when you want to mock functions in certain test cases and restore the
51 * original implementation in others. Beware that mockFn.mockRestore only
52 * works when mock was created with jest.spyOn. Thus you have to take care of
53 * restoration yourself when manually assigning jest.fn().
54 */
55 mockRestore(): void,
56 /**
57 * Accepts a function that should be used as the implementation of the mock.
58 * The mock itself will still record all calls that go into and instances
59 * that come from itself -- the only difference is that the implementation
60 * will also be executed when the mock is called.
61 */
62 mockImplementation(
63 fn: (...args: TArguments) => TReturn
64 ): JestMockFn<TArguments, TReturn>,
65 /**
66 * Accepts a function that will be used as an implementation of the mock for
67 * one call to the mocked function. Can be chained so that multiple function
68 * calls produce different results.
69 */
70 mockImplementationOnce(
71 fn: (...args: TArguments) => TReturn
72 ): JestMockFn<TArguments, TReturn>,
73 /**
74 * Accepts a string to use in test result output in place of "jest.fn()" to
75 * indicate which mock function is being referenced.
76 */
77 mockName(name: string): JestMockFn<TArguments, TReturn>,
78 /**
79 * Just a simple sugar function for returning `this`
80 */
81 mockReturnThis(): void,
82 /**
83 * Accepts a value that will be returned whenever the mock function is called.
84 */
85 mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>,
86 /**
87 * Sugar for only returning a value once inside your mock
88 */
89 mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>,
90 /**
91 * Sugar for jest.fn().mockImplementation(() => Promise.resolve(value))
92 */
93 mockResolvedValue(value: TReturn): JestMockFn<TArguments, Promise<TReturn>>,
94 /**
95 * Sugar for jest.fn().mockImplementationOnce(() => Promise.resolve(value))
96 */
97 mockResolvedValueOnce(
98 value: TReturn
99 ): JestMockFn<TArguments, Promise<TReturn>>,
100 /**
101 * Sugar for jest.fn().mockImplementation(() => Promise.reject(value))
102 */
103 mockRejectedValue(value: TReturn): JestMockFn<TArguments, Promise<any>>,
104 /**
105 * Sugar for jest.fn().mockImplementationOnce(() => Promise.reject(value))
106 */
107 mockRejectedValueOnce(value: TReturn): JestMockFn<TArguments, Promise<any>>,
108 };
109
110 type JestAsymmetricEqualityType = {
111 /**
112 * A custom Jasmine equality tester
113 */
114 asymmetricMatch(value: mixed): boolean,
115 };
116
117 type JestCallsType = {
118 allArgs(): mixed,
119 all(): mixed,
120 any(): boolean,
121 count(): number,
122 first(): mixed,
123 mostRecent(): mixed,
124 reset(): void,
125 };
126
127 type JestClockType = {
128 install(): void,
129 mockDate(date: Date): void,
130 tick(milliseconds?: number): void,
131 uninstall(): void,
132 };
133
134 type JestMatcherResult = {
135 message?: string | (() => string),
136 pass: boolean,
137 };
138
139 type JestMatcher = (
140 actual: any,
141 expected: any
142 ) => JestMatcherResult | Promise<JestMatcherResult>;
143
144 type JestPromiseType = {
145 /**
146 * Use rejects to unwrap the reason of a rejected promise so any other
147 * matcher can be chained. If the promise is fulfilled the assertion fails.
148 */
149 rejects: JestExpectType,
150 /**
151 * Use resolves to unwrap the value of a fulfilled promise so any other
152 * matcher can be chained. If the promise is rejected the assertion fails.
153 */
154 resolves: JestExpectType,
155 };
156
157 /**
158 * Jest allows functions and classes to be used as test names in test() and
159 * describe()
160 */
161 type JestTestName = string | Function;
162
163 /**
164 * Plugin: jest-styled-components
165 */
166
167 type JestStyledComponentsMatcherValue =
168 | string
169 | JestAsymmetricEqualityType
170 | RegExp
171 | typeof undefined;
172
173 type JestStyledComponentsMatcherOptions = {
174 media?: string,
175 modifier?: string,
176 supports?: string,
177 };
178
179 type JestStyledComponentsMatchersType = {
180 toHaveStyleRule(
181 property: string,
182 value: JestStyledComponentsMatcherValue,
183 options?: JestStyledComponentsMatcherOptions
184 ): void,
185 };
186
187 /**
188 * Plugin: jest-enzyme
189 */
190 type EnzymeMatchersType = {
191 // 5.x
192 toBeEmpty(): void,
193 toBePresent(): void,
194 // 6.x
195 toBeChecked(): void,
196 toBeDisabled(): void,
197 toBeEmptyRender(): void,
198 toContainMatchingElement(selector: string): void,
199 toContainMatchingElements(n: number, selector: string): void,
200 toContainExactlyOneMatchingElement(selector: string): void,
201 toContainReact(element: React$Element<any>): void,
202 toExist(): void,
203 toHaveClassName(className: string): void,
204 toHaveHTML(html: string): void,
205 toHaveProp: ((propKey: string, propValue?: any) => void) &
206 ((props: {}) => void),
207 toHaveRef(refName: string): void,
208 toHaveState: ((stateKey: string, stateValue?: any) => void) &
209 ((state: {}) => void),
210 toHaveStyle: ((styleKey: string, styleValue?: any) => void) &
211 ((style: {}) => void),
212 toHaveTagName(tagName: string): void,
213 toHaveText(text: string): void,
214 toHaveValue(value: any): void,
215 toIncludeText(text: string): void,
216 toMatchElement(
217 element: React$Element<any>,
218 options?: {ignoreProps?: boolean, verbose?: boolean}
219 ): void,
220 toMatchSelector(selector: string): void,
221 // 7.x
222 toHaveDisplayName(name: string): void,
223 };
224
225 // DOM testing library extensions https://github.com/kentcdodds/dom-testing-library#custom-jest-matchers
226 type DomTestingLibraryType = {
227 toBeDisabled(): void,
228 toBeEmpty(): void,
229 toBeInTheDocument(): void,
230 toBeVisible(): void,
231 toContainElement(element: HTMLElement | null): void,
232 toContainHTML(htmlText: string): void,
233 toHaveAttribute(name: string, expectedValue?: string): void,
234 toHaveClass(...classNames: string[]): void,
235 toHaveFocus(): void,
236 toHaveFormValues(expectedValues: {[name: string]: any}): void,
237 toHaveStyle(css: string): void,
238 toHaveTextContent(
239 content: string | RegExp,
240 options?: {normalizeWhitespace: boolean}
241 ): void,
242 toBeInTheDOM(): void,
243 };
244
245 // Jest JQuery Matchers: https://github.com/unindented/custom-jquery-matchers
246 type JestJQueryMatchersType = {
247 toExist(): void,
248 toHaveLength(len: number): void,
249 toHaveId(id: string): void,
250 toHaveClass(className: string): void,
251 toHaveTag(tag: string): void,
252 toHaveAttr(key: string, val?: any): void,
253 toHaveProp(key: string, val?: any): void,
254 toHaveText(text: string | RegExp): void,
255 toHaveData(key: string, val?: any): void,
256 toHaveValue(val: any): void,
257 toHaveCss(css: {[key: string]: any}): void,
258 toBeChecked(): void,
259 toBeDisabled(): void,
260 toBeEmpty(): void,
261 toBeHidden(): void,
262 toBeSelected(): void,
263 toBeVisible(): void,
264 toBeFocused(): void,
265 toBeInDom(): void,
266 toBeMatchedBy(sel: string): void,
267 toHaveDescendant(sel: string): void,
268 toHaveDescendantWithText(sel: string, text: string | RegExp): void,
269 };
270
271 // Jest Extended Matchers: https://github.com/jest-community/jest-extended
272 type JestExtendedMatchersType = {
273 /**
274 * Note: Currently unimplemented
275 * Passing assertion
276 *
277 * @param {String} message
278 */
279 // pass(message: string): void;
280
281 /**
282 * Note: Currently unimplemented
283 * Failing assertion
284 *
285 * @param {String} message
286 */
287 // fail(message: string): void;
288
289 /**
290 * Use .toBeEmpty when checking if a String '', Array [] or Object {} is empty.
291 */
292 toBeEmpty(): void,
293
294 /**
295 * Use .toBeOneOf when checking if a value is a member of a given Array.
296 * @param {Array.<*>} members
297 */
298 toBeOneOf(members: any[]): void,
299
300 /**
301 * Use `.toBeNil` when checking a value is `null` or `undefined`.
302 */
303 toBeNil(): void,
304
305 /**
306 * Use `.toSatisfy` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean`.
307 * @param {Function} predicate
308 */
309 toSatisfy(predicate: (n: any) => boolean): void,
310
311 /**
312 * Use `.toBeArray` when checking if a value is an `Array`.
313 */
314 toBeArray(): void,
315
316 /**
317 * Use `.toBeArrayOfSize` when checking if a value is an `Array` of size x.
318 * @param {Number} x
319 */
320 toBeArrayOfSize(x: number): void,
321
322 /**
323 * Use `.toIncludeAllMembers` when checking if an `Array` contains all of the same members of a given set.
324 * @param {Array.<*>} members
325 */
326 toIncludeAllMembers(members: any[]): void,
327
328 /**
329 * Use `.toIncludeAnyMembers` when checking if an `Array` contains any of the members of a given set.
330 * @param {Array.<*>} members
331 */
332 toIncludeAnyMembers(members: any[]): void,
333
334 /**
335 * Use `.toSatisfyAll` when you want to use a custom matcher by supplying a predicate function that returns a `Boolean` for all values in an array.
336 * @param {Function} predicate
337 */
338 toSatisfyAll(predicate: (n: any) => boolean): void,
339
340 /**
341 * Use `.toBeBoolean` when checking if a value is a `Boolean`.
342 */
343 toBeBoolean(): void,
344
345 /**
346 * Use `.toBeTrue` when checking a value is equal (===) to `true`.
347 */
348 toBeTrue(): void,
349
350 /**
351 * Use `.toBeFalse` when checking a value is equal (===) to `false`.
352 */
353 toBeFalse(): void,
354
355 /**
356 * Use .toBeDate when checking if a value is a Date.
357 */
358 toBeDate(): void,
359
360 /**
361 * Use `.toBeFunction` when checking if a value is a `Function`.
362 */
363 toBeFunction(): void,
364
365 /**
366 * Use `.toHaveBeenCalledBefore` when checking if a `Mock` was called before another `Mock`.
367 *
368 * Note: Required Jest version >22
369 * Note: Your mock functions will have to be asynchronous to cause the timestamps inside of Jest to occur in a differentJS event loop, otherwise the mock timestamps will all be the same
370 *
371 * @param {Mock} mock
372 */
373 toHaveBeenCalledBefore(mock: JestMockFn<any, any>): void,
374
375 /**
376 * Use `.toBeNumber` when checking if a value is a `Number`.
377 */
378 toBeNumber(): void,
379
380 /**
381 * Use `.toBeNaN` when checking a value is `NaN`.
382 */
383 toBeNaN(): void,
384
385 /**
386 * Use `.toBeFinite` when checking if a value is a `Number`, not `NaN` or `Infinity`.
387 */
388 toBeFinite(): void,
389
390 /**
391 * Use `.toBePositive` when checking if a value is a positive `Number`.
392 */
393 toBePositive(): void,
394
395 /**
396 * Use `.toBeNegative` when checking if a value is a negative `Number`.
397 */
398 toBeNegative(): void,
399
400 /**
401 * Use `.toBeEven` when checking if a value is an even `Number`.
402 */
403 toBeEven(): void,
404
405 /**
406 * Use `.toBeOdd` when checking if a value is an odd `Number`.
407 */
408 toBeOdd(): void,
409
410 /**
411 * Use `.toBeWithin` when checking if a number is in between the given bounds of: start (inclusive) and end (exclusive).
412 *
413 * @param {Number} start
414 * @param {Number} end
415 */
416 toBeWithin(start: number, end: number): void,
417
418 /**
419 * Use `.toBeObject` when checking if a value is an `Object`.
420 */
421 toBeObject(): void,
422
423 /**
424 * Use `.toContainKey` when checking if an object contains the provided key.
425 *
426 * @param {String} key
427 */
428 toContainKey(key: string): void,
429
430 /**
431 * Use `.toContainKeys` when checking if an object has all of the provided keys.
432 *
433 * @param {Array.<String>} keys
434 */
435 toContainKeys(keys: string[]): void,
436
437 /**
438 * Use `.toContainAllKeys` when checking if an object only contains all of the provided keys.
439 *
440 * @param {Array.<String>} keys
441 */
442 toContainAllKeys(keys: string[]): void,
443
444 /**
445 * Use `.toContainAnyKeys` when checking if an object contains at least one of the provided keys.
446 *
447 * @param {Array.<String>} keys
448 */
449 toContainAnyKeys(keys: string[]): void,
450
451 /**
452 * Use `.toContainValue` when checking if an object contains the provided value.
453 *
454 * @param {*} value
455 */
456 toContainValue(value: any): void,
457
458 /**
459 * Use `.toContainValues` when checking if an object contains all of the provided values.
460 *
461 * @param {Array.<*>} values
462 */
463 toContainValues(values: any[]): void,
464
465 /**
466 * Use `.toContainAllValues` when checking if an object only contains all of the provided values.
467 *
468 * @param {Array.<*>} values
469 */
470 toContainAllValues(values: any[]): void,
471
472 /**
473 * Use `.toContainAnyValues` when checking if an object contains at least one of the provided values.
474 *
475 * @param {Array.<*>} values
476 */
477 toContainAnyValues(values: any[]): void,
478
479 /**
480 * Use `.toContainEntry` when checking if an object contains the provided entry.
481 *
482 * @param {Array.<String, String>} entry
483 */
484 toContainEntry(entry: [string, string]): void,
485
486 /**
487 * Use `.toContainEntries` when checking if an object contains all of the provided entries.
488 *
489 * @param {Array.<Array.<String, String>>} entries
490 */
491 toContainEntries(entries: [string, string][]): void,
492
493 /**
494 * Use `.toContainAllEntries` when checking if an object only contains all of the provided entries.
495 *
496 * @param {Array.<Array.<String, String>>} entries
497 */
498 toContainAllEntries(entries: [string, string][]): void,
499
500 /**
501 * Use `.toContainAnyEntries` when checking if an object contains at least one of the provided entries.
502 *
503 * @param {Array.<Array.<String, String>>} entries
504 */
505 toContainAnyEntries(entries: [string, string][]): void,
506
507 /**
508 * Use `.toBeExtensible` when checking if an object is extensible.
509 */
510 toBeExtensible(): void,
511
512 /**
513 * Use `.toBeFrozen` when checking if an object is frozen.
514 */
515 toBeFrozen(): void,
516
517 /**
518 * Use `.toBeSealed` when checking if an object is sealed.
519 */
520 toBeSealed(): void,
521
522 /**
523 * Use `.toBeString` when checking if a value is a `String`.
524 */
525 toBeString(): void,
526
527 /**
528 * Use `.toEqualCaseInsensitive` when checking if a string is equal (===) to another ignoring the casing of both strings.
529 *
530 * @param {String} string
531 */
532 toEqualCaseInsensitive(string: string): void,
533
534 /**
535 * Use `.toStartWith` when checking if a `String` starts with a given `String` prefix.
536 *
537 * @param {String} prefix
538 */
539 toStartWith(prefix: string): void,
540
541 /**
542 * Use `.toEndWith` when checking if a `String` ends with a given `String` suffix.
543 *
544 * @param {String} suffix
545 */
546 toEndWith(suffix: string): void,
547
548 /**
549 * Use `.toInclude` when checking if a `String` includes the given `String` substring.
550 *
551 * @param {String} substring
552 */
553 toInclude(substring: string): void,
554
555 /**
556 * Use `.toIncludeRepeated` when checking if a `String` includes the given `String` substring the correct number of times.
557 *
558 * @param {String} substring
559 * @param {Number} times
560 */
561 toIncludeRepeated(substring: string, times: number): void,
562
563 /**
564 * Use `.toIncludeMultiple` when checking if a `String` includes all of the given substrings.
565 *
566 * @param {Array.<String>} substring
567 */
568 toIncludeMultiple(substring: string[]): void,
569 };
570
571 interface JestExpectType {
572 not: JestExpectType &
573 EnzymeMatchersType &
574 DomTestingLibraryType &
575 JestJQueryMatchersType &
576 JestStyledComponentsMatchersType &
577 JestExtendedMatchersType;
578 /**
579 * If you have a mock function, you can use .lastCalledWith to test what
580 * arguments it was last called with.
581 */
582 lastCalledWith(...args: Array<any>): void;
583 /**
584 * toBe just checks that a value is what you expect. It uses === to check
585 * strict equality.
586 */
587 toBe(value: any): void;
588 /**
589 * Use .toBeCalledWith to ensure that a mock function was called with
590 * specific arguments.
591 */
592 toBeCalledWith(...args: Array<any>): void;
593 /**
594 * Using exact equality with floating point numbers is a bad idea. Rounding
595 * means that intuitive things fail.
596 */
597 toBeCloseTo(num: number, delta: any): void;
598 /**
599 * Use .toBeDefined to check that a variable is not undefined.
600 */
601 toBeDefined(): void;
602 /**
603 * Use .toBeFalsy when you don't care what a value is, you just want to
604 * ensure a value is false in a boolean context.
605 */
606 toBeFalsy(): void;
607 /**
608 * To compare floating point numbers, you can use toBeGreaterThan.
609 */
610 toBeGreaterThan(number: number): void;
611 /**
612 * To compare floating point numbers, you can use toBeGreaterThanOrEqual.
613 */
614 toBeGreaterThanOrEqual(number: number): void;
615 /**
616 * To compare floating point numbers, you can use toBeLessThan.
617 */
618 toBeLessThan(number: number): void;
619 /**
620 * To compare floating point numbers, you can use toBeLessThanOrEqual.
621 */
622 toBeLessThanOrEqual(number: number): void;
623 /**
624 * Use .toBeInstanceOf(Class) to check that an object is an instance of a
625 * class.
626 */
627 toBeInstanceOf(cls: Class<any>): void;
628 /**
629 * .toBeNull() is the same as .toBe(null) but the error messages are a bit
630 * nicer.
631 */
632 toBeNull(): void;
633 /**
634 * Use .toBeTruthy when you don't care what a value is, you just want to
635 * ensure a value is true in a boolean context.
636 */
637 toBeTruthy(): void;
638 /**
639 * Use .toBeUndefined to check that a variable is undefined.
640 */
641 toBeUndefined(): void;
642 /**
643 * Use .toContain when you want to check that an item is in a list. For
644 * testing the items in the list, this uses ===, a strict equality check.
645 */
646 toContain(item: any): void;
647 /**
648 * Use .toContainEqual when you want to check that an item is in a list. For
649 * testing the items in the list, this matcher recursively checks the
650 * equality of all fields, rather than checking for object identity.
651 */
652 toContainEqual(item: any): void;
653 /**
654 * Use .toEqual when you want to check that two objects have the same value.
655 * This matcher recursively checks the equality of all fields, rather than
656 * checking for object identity.
657 */
658 toEqual(value: any): void;
659 /**
660 * Use .toHaveBeenCalled to ensure that a mock function got called.
661 */
662 toHaveBeenCalled(): void;
663 toBeCalled(): void;
664 /**
665 * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact
666 * number of times.
667 */
668 toHaveBeenCalledTimes(number: number): void;
669 toBeCalledTimes(number: number): void;
670 /**
671 *
672 */
673 toHaveBeenNthCalledWith(nthCall: number, ...args: Array<any>): void;
674 nthCalledWith(nthCall: number, ...args: Array<any>): void;
675 /**
676 *
677 */
678 toHaveReturned(): void;
679 toReturn(): void;
680 /**
681 *
682 */
683 toHaveReturnedTimes(number: number): void;
684 toReturnTimes(number: number): void;
685 /**
686 *
687 */
688 toHaveReturnedWith(value: any): void;
689 toReturnWith(value: any): void;
690 /**
691 *
692 */
693 toHaveLastReturnedWith(value: any): void;
694 lastReturnedWith(value: any): void;
695 /**
696 *
697 */
698 toHaveNthReturnedWith(nthCall: number, value: any): void;
699 nthReturnedWith(nthCall: number, value: any): void;
700 /**
701 * Use .toHaveBeenCalledWith to ensure that a mock function was called with
702 * specific arguments.
703 */
704 toHaveBeenCalledWith(...args: Array<any>): void;
705 /**
706 * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called
707 * with specific arguments.
708 */
709 toHaveBeenLastCalledWith(...args: Array<any>): void;
710 /**
711 * Check that an object has a .length property and it is set to a certain
712 * numeric value.
713 */
714 toHaveLength(number: number): void;
715 /**
716 *
717 */
718 toHaveProperty(propPath: string, value?: any): void;
719 /**
720 * Use .toMatch to check that a string matches a regular expression or string.
721 */
722 toMatch(regexpOrString: RegExp | string): void;
723 /**
724 * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.
725 */
726 toMatchObject(object: Object | Array<Object>): void;
727 /**
728 * Use .toStrictEqual to check that a javascript object matches a subset of the properties of an object.
729 */
730 toStrictEqual(value: any): void;
731 /**
732 * This ensures that an Object matches the most recent snapshot.
733 */
734 toMatchSnapshot(propertyMatchers?: any, name?: string): void;
735 /**
736 * This ensures that an Object matches the most recent snapshot.
737 */
738 toMatchSnapshot(name: string): void;
739
740 toMatchInlineSnapshot(snapshot?: string): void;
741 toMatchInlineSnapshot(propertyMatchers?: any, snapshot?: string): void;
742 /**
743 * Use .toThrow to test that a function throws when it is called.
744 * If you want to test that a specific error gets thrown, you can provide an
745 * argument to toThrow. The argument can be a string for the error message,
746 * a class for the error, or a regex that should match the error.
747 *
748 * Alias: .toThrowError
749 */
750 toThrow(message?: string | Error | Class<Error> | RegExp): void;
751 toThrowError(message?: string | Error | Class<Error> | RegExp): void;
752 /**
753 * Use .toThrowErrorMatchingSnapshot to test that a function throws a error
754 * matching the most recent snapshot when it is called.
755 */
756 toThrowErrorMatchingSnapshot(): void;
757 toThrowErrorMatchingInlineSnapshot(snapshot?: string): void;
758 }
759
760 type JestObjectType = {
761 /**
762 * Disables automatic mocking in the module loader.
763 *
764 * After this method is called, all `require()`s will return the real
765 * versions of each module (rather than a mocked version).
766 */
767 disableAutomock(): JestObjectType,
768 /**
769 * An un-hoisted version of disableAutomock
770 */
771 autoMockOff(): JestObjectType,
772 /**
773 * Enables automatic mocking in the module loader.
774 */
775 enableAutomock(): JestObjectType,
776 /**
777 * An un-hoisted version of enableAutomock
778 */
779 autoMockOn(): JestObjectType,
780 /**
781 * Clears the mock.calls and mock.instances properties of all mocks.
782 * Equivalent to calling .mockClear() on every mocked function.
783 */
784 clearAllMocks(): JestObjectType,
785 /**
786 * Resets the state of all mocks. Equivalent to calling .mockReset() on every
787 * mocked function.
788 */
789 resetAllMocks(): JestObjectType,
790 /**
791 * Restores all mocks back to their original value.
792 */
793 restoreAllMocks(): JestObjectType,
794 /**
795 * Removes any pending timers from the timer system.
796 */
797 clearAllTimers(): void,
798 /**
799 * Returns the number of fake timers still left to run.
800 */
801 getTimerCount(): number,
802 /**
803 * The same as `mock` but not moved to the top of the expectation by
804 * babel-jest.
805 */
806 doMock(moduleName: string, moduleFactory?: any): JestObjectType,
807 /**
808 * The same as `unmock` but not moved to the top of the expectation by
809 * babel-jest.
810 */
811 dontMock(moduleName: string): JestObjectType,
812 /**
813 * Returns a new, unused mock function. Optionally takes a mock
814 * implementation.
815 */
816 fn<TArguments: $ReadOnlyArray<any>, TReturn>(
817 implementation?: (...args: TArguments) => TReturn
818 ): JestMockFn<TArguments, TReturn>,
819 /**
820 * Determines if the given function is a mocked function.
821 */
822 isMockFunction(fn: Function): boolean,
823 /**
824 * Given the name of a module, use the automatic mocking system to generate a
825 * mocked version of the module for you.
826 */
827 genMockFromModule(moduleName: string): any,
828 /**
829 * Mocks a module with an auto-mocked version when it is being required.
830 *
831 * The second argument can be used to specify an explicit module factory that
832 * is being run instead of using Jest's automocking feature.
833 *
834 * The third argument can be used to create virtual mocks -- mocks of modules
835 * that don't exist anywhere in the system.
836 */
837 mock(
838 moduleName: string,
839 moduleFactory?: any,
840 options?: Object
841 ): JestObjectType,
842 /**
843 * Returns the actual module instead of a mock, bypassing all checks on
844 * whether the module should receive a mock implementation or not.
845 */
846 requireActual(moduleName: string): any,
847 /**
848 * Returns a mock module instead of the actual module, bypassing all checks
849 * on whether the module should be required normally or not.
850 */
851 requireMock(moduleName: string): any,
852 /**
853 * Resets the module registry - the cache of all required modules. This is
854 * useful to isolate modules where local state might conflict between tests.
855 */
856 resetModules(): JestObjectType,
857
858 /**
859 * Creates a sandbox registry for the modules that are loaded inside the
860 * callback function. This is useful to isolate specific modules for every
861 * test so that local module state doesn't conflict between tests.
862 */
863 isolateModules(fn: () => void): JestObjectType,
864
865 /**
866 * Exhausts the micro-task queue (usually interfaced in node via
867 * process.nextTick).
868 */
869 runAllTicks(): void,
870 /**
871 * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),
872 * setInterval(), and setImmediate()).
873 */
874 runAllTimers(): void,
875 /**
876 * Exhausts all tasks queued by setImmediate().
877 */
878 runAllImmediates(): void,
879 /**
880 * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
881 * or setInterval() and setImmediate()).
882 */
883 advanceTimersByTime(msToRun: number): void,
884 /**
885 * Executes only the macro task queue (i.e. all tasks queued by setTimeout()
886 * or setInterval() and setImmediate()).
887 *
888 * Renamed to `advanceTimersByTime`.
889 */
890 runTimersToTime(msToRun: number): void,
891 /**
892 * Executes only the macro-tasks that are currently pending (i.e., only the
893 * tasks that have been queued by setTimeout() or setInterval() up to this
894 * point)
895 */
896 runOnlyPendingTimers(): void,
897 /**
898 * Explicitly supplies the mock object that the module system should return
899 * for the specified module. Note: It is recommended to use jest.mock()
900 * instead.
901 */
902 setMock(moduleName: string, moduleExports: any): JestObjectType,
903 /**
904 * Indicates that the module system should never return a mocked version of
905 * the specified module from require() (e.g. that it should always return the
906 * real module).
907 */
908 unmock(moduleName: string): JestObjectType,
909 /**
910 * Instructs Jest to use fake versions of the standard timer functions
911 * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,
912 * setImmediate and clearImmediate).
913 */
914 useFakeTimers(): JestObjectType,
915 /**
916 * Instructs Jest to use the real versions of the standard timer functions.
917 */
918 useRealTimers(): JestObjectType,
919 /**
920 * Creates a mock function similar to jest.fn but also tracks calls to
921 * object[methodName].
922 */
923 spyOn(
924 object: Object,
925 methodName: string,
926 accessType?: 'get' | 'set'
927 ): JestMockFn<any, any>,
928 /**
929 * Set the default timeout interval for tests and before/after hooks in milliseconds.
930 * Note: The default timeout interval is 5 seconds if this method is not called.
931 */
932 setTimeout(timeout: number): JestObjectType,
933 };
934
935 type JestSpyType = {
936 calls: JestCallsType,
937 };
938
939 /** Runs this function after every test inside this context */
940 declare function afterEach(
941 fn: (done: () => void) => ?Promise<mixed>,
942 timeout?: number
943 ): void;
944 /** Runs this function before every test inside this context */
945 declare function beforeEach(
946 fn: (done: () => void) => ?Promise<mixed>,
947 timeout?: number
948 ): void;
949 /** Runs this function after all tests have finished inside this context */
950 declare function afterAll(
951 fn: (done: () => void) => ?Promise<mixed>,
952 timeout?: number
953 ): void;
954 /** Runs this function before any tests have started inside this context */
955 declare function beforeAll(
956 fn: (done: () => void) => ?Promise<mixed>,
957 timeout?: number
958 ): void;
959
960 /** A context for grouping tests together */
961 declare const describe: {
962 /**
963 * Creates a block that groups together several related tests in one "test suite"
964 */
965 (name: JestTestName, fn: () => void): void,
966
967 /**
968 * Only run this describe block
969 */
970 only(name: JestTestName, fn: () => void): void,
971
972 /**
973 * Skip running this describe block
974 */
975 skip(name: JestTestName, fn: () => void): void,
976
977 /**
978 * each runs this test against array of argument arrays per each run
979 *
980 * @param {table} table of Test
981 */
982 each(
983 ...table: Array<Array<mixed> | mixed> | [Array<string>, string]
984 ): (
985 name: JestTestName,
986 fn?: (...args: Array<any>) => ?Promise<mixed>,
987 timeout?: number
988 ) => void,
989 };
990
991 /** An individual test unit */
992 declare const it: {
993 /**
994 * An individual test unit
995 *
996 * @param {JestTestName} Name of Test
997 * @param {Function} Test
998 * @param {number} Timeout for the test, in milliseconds.
999 */
1000 (
1001 name: JestTestName,
1002 fn?: (done: () => void) => ?Promise<mixed>,
1003 timeout?: number
1004 ): void,
1005
1006 /**
1007 * Only run this test
1008 *
1009 * @param {JestTestName} Name of Test
1010 * @param {Function} Test
1011 * @param {number} Timeout for the test, in milliseconds.
1012 */
1013 only(
1014 name: JestTestName,
1015 fn?: (done: () => void) => ?Promise<mixed>,
1016 timeout?: number
1017 ): {
1018 each(
1019 ...table: Array<Array<mixed> | mixed> | [Array<string>, string]
1020 ): (
1021 name: JestTestName,
1022 fn?: (...args: Array<any>) => ?Promise<mixed>,
1023 timeout?: number
1024 ) => void,
1025 },
1026
1027 /**
1028 * Skip running this test
1029 *
1030 * @param {JestTestName} Name of Test
1031 * @param {Function} Test
1032 * @param {number} Timeout for the test, in milliseconds.
1033 */
1034 skip(
1035 name: JestTestName,
1036 fn?: (done: () => void) => ?Promise<mixed>,
1037 timeout?: number
1038 ): void,
1039
1040 /**
1041 * Highlight planned tests in the summary output
1042 *
1043 * @param {String} Name of Test to do
1044 */
1045 todo(name: string): void,
1046
1047 /**
1048 * Run the test concurrently
1049 *
1050 * @param {JestTestName} Name of Test
1051 * @param {Function} Test
1052 * @param {number} Timeout for the test, in milliseconds.
1053 */
1054 concurrent(
1055 name: JestTestName,
1056 fn?: (done: () => void) => ?Promise<mixed>,
1057 timeout?: number
1058 ): void,
1059
1060 /**
1061 * each runs this test against array of argument arrays per each run
1062 *
1063 * @param {table} table of Test
1064 */
1065 each(
1066 ...table: Array<Array<mixed> | mixed> | [Array<string>, string]
1067 ): (
1068 name: JestTestName,
1069 fn?: (...args: Array<any>) => ?Promise<mixed>,
1070 timeout?: number
1071 ) => void,
1072 };
1073
1074 declare function fit(
1075 name: JestTestName,
1076 fn: (done: () => void) => ?Promise<mixed>,
1077 timeout?: number
1078 ): void;
1079 /** An individual test unit */
1080 declare const test: typeof it;
1081 /** A disabled group of tests */
1082 declare const xdescribe: typeof describe;
1083 /** A focused group of tests */
1084 declare const fdescribe: typeof describe;
1085 /** A disabled individual test */
1086 declare const xit: typeof it;
1087 /** A disabled individual test */
1088 declare const xtest: typeof it;
1089
1090 type JestPrettyFormatColors = {
1091 comment: {close: string, open: string},
1092 content: {close: string, open: string},
1093 prop: {close: string, open: string},
1094 tag: {close: string, open: string},
1095 value: {close: string, open: string},
1096 };
1097
1098 type JestPrettyFormatIndent = string => string;
1099 type JestPrettyFormatRefs = Array<any>;
1100 type JestPrettyFormatPrint = any => string;
1101 type JestPrettyFormatStringOrNull = string | null;
1102
1103 type JestPrettyFormatOptions = {
1104 callToJSON: boolean,
1105 edgeSpacing: string,
1106 escapeRegex: boolean,
1107 highlight: boolean,
1108 indent: number,
1109 maxDepth: number,
1110 min: boolean,
1111 plugins: JestPrettyFormatPlugins,
1112 printFunctionName: boolean,
1113 spacing: string,
1114 theme: {
1115 comment: string,
1116 content: string,
1117 prop: string,
1118 tag: string,
1119 value: string,
1120 },
1121 };
1122
1123 type JestPrettyFormatPlugin = {
1124 print: (
1125 val: any,
1126 serialize: JestPrettyFormatPrint,
1127 indent: JestPrettyFormatIndent,
1128 opts: JestPrettyFormatOptions,
1129 colors: JestPrettyFormatColors
1130 ) => string,
1131 test: any => boolean,
1132 };
1133
1134 type JestPrettyFormatPlugins = Array<JestPrettyFormatPlugin>;
1135
1136 /** The expect function is used every time you want to test a value */
1137 declare const expect: {
1138 /** The object that you want to make assertions against */
1139 (
1140 value: any
1141 ): JestExpectType &
1142 JestPromiseType &
1143 EnzymeMatchersType &
1144 DomTestingLibraryType &
1145 JestJQueryMatchersType &
1146 JestStyledComponentsMatchersType &
1147 JestExtendedMatchersType,
1148
1149 /** Add additional Jasmine matchers to Jest's roster */
1150 extend(matchers: {[name: string]: JestMatcher}): void,
1151 /** Add a module that formats application-specific data structures. */
1152 addSnapshotSerializer(pluginModule: JestPrettyFormatPlugin): void,
1153 assertions(expectedAssertions: number): void,
1154 hasAssertions(): void,
1155 any(value: mixed): JestAsymmetricEqualityType,
1156 anything(): any,
1157 arrayContaining(value: Array<mixed>): Array<mixed>,
1158 objectContaining(value: Object): Object,
1159 /** Matches any received string that contains the exact expected string. */
1160 stringContaining(value: string): string,
1161 stringMatching(value: string | RegExp): string,
1162 not: {
1163 arrayContaining: (value: $ReadOnlyArray<mixed>) => Array<mixed>,
1164 objectContaining: (value: {}) => Object,
1165 stringContaining: (value: string) => string,
1166 stringMatching: (value: string | RegExp) => string,
1167 },
1168 };
1169
1170 /** Holds all functions related to manipulating test runner */
1171 declare const jest: JestObjectType;