index.d.ts 9.7 KB

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