UNPKG

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