UNPKG

10.5 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" />
8import type { Context } from 'vm';
9import type { LegacyFakeTimers, ModernFakeTimers } from '@jest/fake-timers';
10import type { Circus, Config, Global } from '@jest/types';
11import type { fn as JestMockFn, mocked as JestMockMocked, spyOn as JestMockSpyOn, ModuleMocker } from 'jest-mock';
12export declare type EnvironmentContext = {
13 console: Console;
14 docblockPragmas: Record<string, string | Array<string>>;
15 testPath: Config.Path;
16};
17export declare type ModuleWrapper = (this: Module['exports'], module: Module, exports: Module['exports'], require: Module['require'], __dirname: string, __filename: Module['filename'], jest?: Jest, ...extraGlobals: Array<Global.Global[keyof Global.Global]>) => unknown;
18export declare class JestEnvironment<Timer = unknown> {
19 constructor(config: Config.ProjectConfig, context?: EnvironmentContext);
20 global: Global.Global;
21 fakeTimers: LegacyFakeTimers<Timer> | null;
22 fakeTimersModern: ModernFakeTimers | null;
23 moduleMocker: ModuleMocker | null;
24 getVmContext(): Context | null;
25 setup(): Promise<void>;
26 teardown(): Promise<void>;
27 handleTestEvent?: Circus.EventHandler;
28 exportConditions?: () => Array<string>;
29}
30export declare type Module = NodeModule;
31export interface Jest {
32 /**
33 * Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run.
34 * Optionally, you can provide steps, so it will 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 and mock.instances properties of all mocks.
47 * 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 * Indicates that the module system should never return a mocked version
58 * of the specified module, including all of the specified module's
59 * dependencies.
60 */
61 deepUnmock(moduleName: string): Jest;
62 /**
63 * Disables automatic mocking in the module loader.
64 *
65 * After this method is called, all `require()`s will return the real
66 * versions of each module (rather than a mocked version).
67 */
68 disableAutomock(): Jest;
69 /**
70 * When using `babel-jest`, calls to mock will automatically be hoisted to
71 * the top of the code block. Use this method if you want to explicitly avoid
72 * this behavior.
73 */
74 doMock(moduleName: string, moduleFactory?: () => unknown): Jest;
75 /**
76 * Indicates that the module system should never return a mocked version
77 * of the specified module from require() (e.g. that it should always return
78 * the real module).
79 */
80 dontMock(moduleName: string): Jest;
81 /**
82 * Enables automatic mocking in the module loader.
83 */
84 enableAutomock(): Jest;
85 /**
86 * Creates a mock function. Optionally takes a mock implementation.
87 */
88 fn: typeof JestMockFn;
89 /**
90 * Given the name of a module, use the automatic mocking system to generate a
91 * mocked version of the module for you.
92 *
93 * This is useful when you want to create a manual mock that extends the
94 * automatic mock's behavior.
95 *
96 * @deprecated Use `jest.createMockFromModule()` instead
97 */
98 genMockFromModule(moduleName: string): unknown;
99 /**
100 * Given the name of a module, use the automatic mocking system to generate a
101 * mocked version of the module for you.
102 *
103 * This is useful when you want to create a manual mock that extends the
104 * automatic mock's behavior.
105 */
106 createMockFromModule(moduleName: string): unknown;
107 /**
108 * Determines if the given function is a mocked function.
109 */
110 isMockFunction(fn: (...args: Array<any>) => unknown): fn is ReturnType<typeof JestMockFn>;
111 /**
112 * Mocks a module with an auto-mocked version when it is being required.
113 */
114 mock(moduleName: string, moduleFactory?: () => unknown, options?: {
115 virtual?: boolean;
116 }): Jest;
117 /**
118 * Mocks a module with the provided module factory when it is being imported.
119 */
120 unstable_mockModule<T = unknown>(moduleName: string, moduleFactory: () => Promise<T> | T, options?: {
121 virtual?: boolean;
122 }): Jest;
123 /**
124 * Returns the actual module instead of a mock, bypassing all checks on
125 * whether the module should receive a mock implementation or not.
126 *
127 * @example
128 ```
129 jest.mock('../myModule', () => {
130 // Require the original module to not be mocked...
131 const originalModule = jest.requireActual(moduleName);
132 return {
133 __esModule: true, // Use it when dealing with esModules
134 ...originalModule,
135 getRandom: jest.fn().mockReturnValue(10),
136 };
137 });
138
139 const getRandom = require('../myModule').getRandom;
140
141 getRandom(); // Always returns 10
142 ```
143 */
144 requireActual: (moduleName: string) => unknown;
145 /**
146 * Returns a mock module instead of the actual module, bypassing all checks
147 * on whether the module should be required normally or not.
148 */
149 requireMock: (moduleName: string) => unknown;
150 /**
151 * Resets the state of all mocks.
152 * Equivalent to calling .mockReset() on every mocked function.
153 */
154 resetAllMocks(): Jest;
155 /**
156 * Resets the module registry - the cache of all required modules. This is
157 * useful to isolate modules where local state might conflict between tests.
158 */
159 resetModules(): Jest;
160 /**
161 * Restores all mocks back to their original value. Equivalent to calling
162 * `.mockRestore` on every mocked function.
163 *
164 * Beware that jest.restoreAllMocks() only works when the mock was created with
165 * jest.spyOn; other mocks will require you to manually restore them.
166 */
167 restoreAllMocks(): Jest;
168 mocked: typeof JestMockMocked;
169 /**
170 * Runs failed tests n-times until they pass or until the max number of
171 * retries is exhausted. This only works with `jest-circus`!
172 */
173 retryTimes(numRetries: number): Jest;
174 /**
175 * Exhausts tasks queued by setImmediate().
176 *
177 * > Note: This function is not available when using Lolex as fake timers implementation
178 */
179 runAllImmediates(): void;
180 /**
181 * Exhausts the micro-task queue (usually interfaced in node via
182 * process.nextTick).
183 */
184 runAllTicks(): void;
185 /**
186 * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout()
187 * and setInterval()).
188 */
189 runAllTimers(): void;
190 /**
191 * Executes only the macro-tasks that are currently pending (i.e., only the
192 * tasks that have been queued by setTimeout() or setInterval() up to this
193 * point). If any of the currently pending macro-tasks schedule new
194 * macro-tasks, those new tasks will not be executed by this call.
195 */
196 runOnlyPendingTimers(): void;
197 /**
198 * Advances all timers by msToRun milliseconds. All pending "macro-tasks"
199 * that have been queued via setTimeout() or setInterval(), and would be
200 * executed within this timeframe will be executed.
201 */
202 advanceTimersByTime(msToRun: number): void;
203 /**
204 * Returns the number of fake timers still left to run.
205 */
206 getTimerCount(): number;
207 /**
208 * Explicitly supplies the mock object that the module system should return
209 * for the specified module.
210 *
211 * Note It is recommended to use `jest.mock()` instead. The `jest.mock`
212 * API's second argument is a module factory instead of the expected
213 * exported module object.
214 */
215 setMock(moduleName: string, moduleExports: unknown): Jest;
216 /**
217 * Set the default timeout interval for tests and before/after hooks in
218 * milliseconds.
219 *
220 * Note: The default timeout interval is 5 seconds if this method is not
221 * called.
222 */
223 setTimeout(timeout: number): Jest;
224 /**
225 * Creates a mock function similar to `jest.fn` but also tracks calls to
226 * `object[methodName]`.
227 *
228 * Note: By default, jest.spyOn also calls the spied method. This is
229 * different behavior from most other test libraries.
230 */
231 spyOn: typeof JestMockSpyOn;
232 /**
233 * Indicates that the module system should never return a mocked version of
234 * the specified module from require() (e.g. that it should always return the
235 * real module).
236 */
237 unmock(moduleName: string): Jest;
238 /**
239 * Instructs Jest to use fake versions of the standard timer functions.
240 */
241 useFakeTimers(implementation?: 'modern' | 'legacy'): Jest;
242 /**
243 * Instructs Jest to use the real versions of the standard timer functions.
244 */
245 useRealTimers(): Jest;
246 /**
247 * `jest.isolateModules(fn)` goes a step further than `jest.resetModules()`
248 * and creates a sandbox registry for the modules that are loaded inside
249 * the callback function. This is useful to isolate specific modules for
250 * every test so that local module state doesn't conflict between tests.
251 */
252 isolateModules(fn: () => void): Jest;
253 /**
254 * When mocking time, `Date.now()` will also be mocked. If you for some reason need access to the real current time, you can invoke this function.
255 *
256 * > Note: This function is only available when using Lolex as fake timers implementation
257 */
258 getRealSystemTime(): number;
259 /**
260 * Set the current system time used by fake timers. Simulates a user changing the system clock while your program is running. It affects the current time but it does not in itself cause e.g. timers to fire; they will fire exactly as they would have done without the call to `jest.setSystemTime()`.
261 *
262 * > Note: This function is only available when using Lolex as fake timers implementation
263 */
264 setSystemTime(now?: number | Date): void;
265}