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