index.d.ts 11 KB

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