index.d.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  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. import type { Context } from 'vm';
  9. import type { LegacyFakeTimers, ModernFakeTimers } from '@jest/fake-timers';
  10. import type { Circus, Config, Global } from '@jest/types';
  11. import type { fn as JestMockFn, mocked as JestMockMocked, spyOn as JestMockSpyOn, ModuleMocker } from 'jest-mock';
  12. export declare type EnvironmentContext = {
  13. console: Console;
  14. docblockPragmas: Record<string, string | Array<string>>;
  15. testPath: Config.Path;
  16. };
  17. export 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;
  18. export 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. }
  30. export declare type Module = NodeModule;
  31. export 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, options?: {
  75. virtual?: boolean;
  76. }): Jest;
  77. /**
  78. * Indicates that the module system should never return a mocked version
  79. * of the specified module from require() (e.g. that it should always return
  80. * the real module).
  81. */
  82. dontMock(moduleName: string): Jest;
  83. /**
  84. * Enables automatic mocking in the module loader.
  85. */
  86. enableAutomock(): Jest;
  87. /**
  88. * Creates a mock function. Optionally takes a mock implementation.
  89. */
  90. fn: typeof JestMockFn;
  91. /**
  92. * Given the name of a module, use the automatic mocking system to generate a
  93. * mocked version of the module for you.
  94. *
  95. * This is useful when you want to create a manual mock that extends the
  96. * automatic mock's behavior.
  97. *
  98. * @deprecated Use `jest.createMockFromModule()` instead
  99. */
  100. genMockFromModule(moduleName: string): unknown;
  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. createMockFromModule(moduleName: string): unknown;
  109. /**
  110. * Determines if the given function is a mocked function.
  111. */
  112. isMockFunction(fn: (...args: Array<any>) => unknown): fn is ReturnType<typeof JestMockFn>;
  113. /**
  114. * Mocks a module with an auto-mocked version when it is being required.
  115. */
  116. mock(moduleName: string, moduleFactory?: () => unknown, options?: {
  117. virtual?: boolean;
  118. }): Jest;
  119. /**
  120. * Mocks a module with the provided module factory when it is being imported.
  121. */
  122. unstable_mockModule<T = unknown>(moduleName: string, moduleFactory: () => Promise<T> | T, options?: {
  123. virtual?: boolean;
  124. }): Jest;
  125. /**
  126. * Returns the actual module instead of a mock, bypassing all checks on
  127. * whether the module should receive a mock implementation or not.
  128. *
  129. * @example
  130. ```
  131. jest.mock('../myModule', () => {
  132. // Require the original module to not be mocked...
  133. const originalModule = jest.requireActual(moduleName);
  134. return {
  135. __esModule: true, // Use it when dealing with esModules
  136. ...originalModule,
  137. getRandom: jest.fn().mockReturnValue(10),
  138. };
  139. });
  140. const getRandom = require('../myModule').getRandom;
  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. }