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