UNPKG

14 kBTypeScriptView Raw
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7/// <reference types="node" />
8
9import type {Circus} from '@jest/types';
10import type {Config} from '@jest/types';
11import type {Context} from 'vm';
12import type {Global} from '@jest/types';
13import type {LegacyFakeTimers} from '@jest/fake-timers';
14import type {Mocked} from 'jest-mock';
15import type {ModernFakeTimers} from '@jest/fake-timers';
16import type {ModuleMocker} from 'jest-mock';
17
18export declare type EnvironmentContext = {
19 console: Console;
20 docblockPragmas: Record<string, string | Array<string>>;
21 testPath: string;
22};
23
24export declare interface Jest {
25 /**
26 * Advances all timers by `msToRun` milliseconds. All pending "macro-tasks"
27 * that have been queued via `setTimeout()` or `setInterval()`, and would be
28 * executed within this time frame will be executed.
29 */
30 advanceTimersByTime(msToRun: number): void;
31 /**
32 * Advances all timers by `msToRun` milliseconds, firing callbacks if necessary.
33 *
34 * @remarks
35 * Not available when using legacy fake timers implementation.
36 */
37 advanceTimersByTimeAsync(msToRun: number): Promise<void>;
38 /**
39 * Advances all timers by the needed milliseconds so that only the next
40 * timeouts/intervals will run. Optionally, you can provide steps, so it will
41 * run steps amount of next timeouts/intervals.
42 */
43 advanceTimersToNextTimer(steps?: number): void;
44 /**
45 * Advances the clock to the the moment of the first scheduled timer, firing it.
46 * Optionally, you can provide steps, so it will run steps amount of
47 * next timeouts/intervals.
48 *
49 * @remarks
50 * Not available when using legacy fake timers implementation.
51 */
52 advanceTimersToNextTimerAsync(steps?: number): Promise<void>;
53 /**
54 * Disables automatic mocking in the module loader.
55 */
56 autoMockOff(): Jest;
57 /**
58 * Enables automatic mocking in the module loader.
59 */
60 autoMockOn(): Jest;
61 /**
62 * Clears the `mock.calls`, `mock.instances`, `mock.contexts` and `mock.results` properties of
63 * all mocks. Equivalent to calling `.mockClear()` on every mocked function.
64 */
65 clearAllMocks(): Jest;
66 /**
67 * Removes any pending timers from the timer system. If any timers have been
68 * scheduled, they will be cleared and will never have the opportunity to
69 * execute in the future.
70 */
71 clearAllTimers(): void;
72 /**
73 * Given the name of a module, use the automatic mocking system to generate a
74 * mocked version of the module for you.
75 *
76 * This is useful when you want to create a manual mock that extends the
77 * automatic mock's behavior.
78 */
79 createMockFromModule<T = unknown>(moduleName: string): Mocked<T>;
80 /**
81 * Indicates that the module system should never return a mocked version of
82 * the specified module and its dependencies.
83 */
84 deepUnmock(moduleName: string): Jest;
85 /**
86 * Disables automatic mocking in the module loader.
87 *
88 * After this method is called, all `require()`s will return the real
89 * versions of each module (rather than a mocked version).
90 */
91 disableAutomock(): Jest;
92 /**
93 * When using `babel-jest`, calls to `jest.mock()` will automatically be hoisted
94 * to the top of the code block. Use this method if you want to explicitly
95 * avoid this behavior.
96 */
97 doMock<T = unknown>(
98 moduleName: string,
99 moduleFactory?: () => T,
100 options?: {
101 virtual?: boolean;
102 },
103 ): Jest;
104 /**
105 * When using `babel-jest`, calls to `jest.unmock()` will automatically be hoisted
106 * to the top of the code block. Use this method if you want to explicitly
107 * avoid this behavior.
108 */
109 dontMock(moduleName: string): Jest;
110 /**
111 * Enables automatic mocking in the module loader.
112 */
113 enableAutomock(): Jest;
114 /**
115 * Creates a mock function. Optionally takes a mock implementation.
116 */
117 fn: ModuleMocker['fn'];
118 /**
119 * Given the name of a module, use the automatic mocking system to generate a
120 * mocked version of the module for you.
121 *
122 * This is useful when you want to create a manual mock that extends the
123 * automatic mock's behavior.
124 *
125 * @deprecated Use `jest.createMockFromModule()` instead
126 */
127 genMockFromModule<T = unknown>(moduleName: string): Mocked<T>;
128 /**
129 * When mocking time, `Date.now()` will also be mocked. If you for some reason
130 * need access to the real current time, you can invoke this function.
131 *
132 * @remarks
133 * Not available when using legacy fake timers implementation.
134 */
135 getRealSystemTime(): number;
136 /**
137 * Retrieves the seed value. It will be randomly generated for each test run
138 * or can be manually set via the `--seed` CLI argument.
139 */
140 getSeed(): number;
141 /**
142 * Returns the number of fake timers still left to run.
143 */
144 getTimerCount(): number;
145 /**
146 * Returns `true` if test environment has been torn down.
147 *
148 * @example
149 * ```js
150 * if (jest.isEnvironmentTornDown()) {
151 * // The Jest environment has been torn down, so stop doing work
152 * return;
153 * }
154 * ```
155 */
156 isEnvironmentTornDown(): boolean;
157 /**
158 * Determines if the given function is a mocked function.
159 */
160 isMockFunction: ModuleMocker['isMockFunction'];
161 /**
162 * `jest.isolateModules()` goes a step further than `jest.resetModules()` and
163 * creates a sandbox registry for the modules that are loaded inside the callback
164 * function. This is useful to isolate specific modules for every test so that
165 * local module state doesn't conflict between tests.
166 */
167 isolateModules(fn: () => void): Jest;
168 /**
169 * `jest.isolateModulesAsync()` is the equivalent of `jest.isolateModules()`, but for
170 * async functions to be wrapped. The caller is expected to `await` the completion of
171 * `isolateModulesAsync`.
172 */
173 isolateModulesAsync(fn: () => Promise<void>): Promise<void>;
174 /**
175 * Mocks a module with an auto-mocked version when it is being required.
176 */
177 mock<T = unknown>(
178 moduleName: string,
179 moduleFactory?: () => T,
180 options?: {
181 virtual?: boolean;
182 },
183 ): Jest;
184 /**
185 * Mocks a module with the provided module factory when it is being imported.
186 */
187 unstable_mockModule<T = unknown>(
188 moduleName: string,
189 moduleFactory: () => T | Promise<T>,
190 options?: {
191 virtual?: boolean;
192 },
193 ): Jest;
194 /**
195 * Wraps types of the `source` object and its deep members with type definitions
196 * of Jest mock function. Pass `{shallow: true}` option to disable the deeply
197 * mocked behavior.
198 */
199 mocked: ModuleMocker['mocked'];
200 /**
201 * Returns the current time in ms of the fake timer clock.
202 */
203 now(): number;
204 /**
205 * Replaces property on an object with another value.
206 *
207 * @remarks
208 * For mocking functions or 'get' or 'set' accessors, use `jest.spyOn()` instead.
209 */
210 replaceProperty: ModuleMocker['replaceProperty'];
211 /**
212 * Returns the actual module instead of a mock, bypassing all checks on
213 * whether the module should receive a mock implementation or not.
214 *
215 * @example
216 * ```js
217 * jest.mock('../myModule', () => {
218 * // Require the original module to not be mocked...
219 * const originalModule = jest.requireActual('../myModule');
220 *
221 * return {
222 * __esModule: true, // Use it when dealing with esModules
223 * ...originalModule,
224 * getRandom: jest.fn().mockReturnValue(10),
225 * };
226 * });
227 *
228 * const getRandom = require('../myModule').getRandom;
229 *
230 * getRandom(); // Always returns 10
231 * ```
232 */
233 requireActual<T = unknown>(moduleName: string): T;
234 /**
235 * Returns a mock module instead of the actual module, bypassing all checks
236 * on whether the module should be required normally or not.
237 */
238 requireMock<T = unknown>(moduleName: string): T;
239 /**
240 * Resets the state of all mocks. Equivalent to calling `.mockReset()` on
241 * every mocked function.
242 */
243 resetAllMocks(): Jest;
244 /**
245 * Resets the module registry - the cache of all required modules. This is
246 * useful to isolate modules where local state might conflict between tests.
247 */
248 resetModules(): Jest;
249 /**
250 * Restores all mocks and replaced properties back to their original value.
251 * Equivalent to calling `.mockRestore()` on every mocked function
252 * and `.restore()` on every replaced property.
253 *
254 * Beware that `jest.restoreAllMocks()` only works when the mock was created
255 * with `jest.spyOn()`; other mocks will require you to manually restore them.
256 */
257 restoreAllMocks(): Jest;
258 /**
259 * Runs failed tests n-times until they pass or until the max number of
260 * retries is exhausted.
261 *
262 * If `logErrorsBeforeRetry` is enabled, Jest will log the error(s) that caused
263 * the test to fail to the console, providing visibility on why a retry occurred.
264 * retries is exhausted.
265 *
266 * @remarks
267 * Only available with `jest-circus` runner.
268 */
269 retryTimes(
270 numRetries: number,
271 options?: {
272 logErrorsBeforeRetry?: boolean;
273 },
274 ): Jest;
275 /**
276 * Exhausts tasks queued by `setImmediate()`.
277 *
278 * @remarks
279 * Only available when using legacy fake timers implementation.
280 */
281 runAllImmediates(): void;
282 /**
283 * Exhausts the micro-task queue (usually interfaced in node via
284 * `process.nextTick()`).
285 */
286 runAllTicks(): void;
287 /**
288 * Exhausts the macro-task queue (i.e., all tasks queued by `setTimeout()`
289 * and `setInterval()`).
290 */
291 runAllTimers(): void;
292 /**
293 * Exhausts the macro-task queue (i.e., all tasks queued by `setTimeout()`
294 * and `setInterval()`).
295 *
296 * @remarks
297 * If new timers are added while it is executing they will be run as well.
298 * @remarks
299 * Not available when using legacy fake timers implementation.
300 */
301 runAllTimersAsync(): Promise<void>;
302 /**
303 * Executes only the macro-tasks that are currently pending (i.e., only the
304 * tasks that have been queued by `setTimeout()` or `setInterval()` up to this
305 * point). If any of the currently pending macro-tasks schedule new
306 * macro-tasks, those new tasks will not be executed by this call.
307 */
308 runOnlyPendingTimers(): void;
309 /**
310 * Executes only the macro-tasks that are currently pending (i.e., only the
311 * tasks that have been queued by `setTimeout()` or `setInterval()` up to this
312 * point). If any of the currently pending macro-tasks schedule new
313 * macro-tasks, those new tasks will not be executed by this call.
314 *
315 * @remarks
316 * Not available when using legacy fake timers implementation.
317 */
318 runOnlyPendingTimersAsync(): Promise<void>;
319 /**
320 * Explicitly supplies the mock object that the module system should return
321 * for the specified module.
322 *
323 * @remarks
324 * It is recommended to use `jest.mock()` instead. The `jest.mock()` API's second
325 * argument is a module factory instead of the expected exported module object.
326 */
327 setMock(moduleName: string, moduleExports: unknown): Jest;
328 /**
329 * Set the current system time used by fake timers. Simulates a user changing
330 * the system clock while your program is running. It affects the current time,
331 * but it does not in itself cause e.g. timers to fire; they will fire exactly
332 * as they would have done without the call to `jest.setSystemTime()`.
333 *
334 * @remarks
335 * Not available when using legacy fake timers implementation.
336 */
337 setSystemTime(now?: number | Date): void;
338 /**
339 * Set the default timeout interval for tests and before/after hooks in
340 * milliseconds.
341 *
342 * @remarks
343 * The default timeout interval is 5 seconds if this method is not called.
344 */
345 setTimeout(timeout: number): Jest;
346 /**
347 * Creates a mock function similar to `jest.fn()` but also tracks calls to
348 * `object[methodName]`.
349 *
350 * Optional third argument of `accessType` can be either 'get' or 'set', which
351 * proves to be useful when you want to spy on a getter or a setter, respectively.
352 *
353 * @remarks
354 * By default, `jest.spyOn()` also calls the spied method. This is different
355 * behavior from most other test libraries.
356 */
357 spyOn: ModuleMocker['spyOn'];
358 /**
359 * Indicates that the module system should never return a mocked version of
360 * the specified module from `require()` (e.g. that it should always return the
361 * real module).
362 */
363 unmock(moduleName: string): Jest;
364 /**
365 * Instructs Jest to use fake versions of the global date, performance,
366 * time and timer APIs. Fake timers implementation is backed by
367 * [`@sinonjs/fake-timers`](https://github.com/sinonjs/fake-timers).
368 *
369 * @remarks
370 * Calling `jest.useFakeTimers()` once again in the same test file would reinstall
371 * fake timers using the provided options.
372 */
373 useFakeTimers(
374 fakeTimersConfig?: Config.FakeTimersConfig | Config.LegacyFakeTimersConfig,
375 ): Jest;
376 /**
377 * Instructs Jest to restore the original implementations of the global date,
378 * performance, time and timer APIs.
379 */
380 useRealTimers(): Jest;
381}
382
383export declare class JestEnvironment<Timer = unknown> {
384 constructor(config: JestEnvironmentConfig, context: EnvironmentContext);
385 global: Global.Global;
386 fakeTimers: LegacyFakeTimers<Timer> | null;
387 fakeTimersModern: ModernFakeTimers | null;
388 moduleMocker: ModuleMocker | null;
389 getVmContext(): Context | null;
390 setup(): Promise<void>;
391 teardown(): Promise<void>;
392 handleTestEvent?: Circus.EventHandler;
393 exportConditions?: () => Array<string>;
394}
395
396export declare interface JestEnvironmentConfig {
397 projectConfig: Config.ProjectConfig;
398 globalConfig: Config.GlobalConfig;
399}
400
401export declare interface JestImportMeta extends ImportMeta {
402 jest: Jest;
403}
404
405export declare type Module = NodeModule;
406
407export declare type ModuleWrapper = (
408 this: Module['exports'],
409 module: Module,
410 exports: Module['exports'],
411 require: Module['require'],
412 __dirname: string,
413 __filename: Module['filename'],
414 jest?: Jest,
415 ...sandboxInjectedGlobals: Array<Global.Global[keyof Global.Global]>
416) => unknown;
417
418export {};