UNPKG

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