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