@jest/environment

  • Version 28.1.2
  • Published
  • 13.2 kB
  • 4 dependencies
  • MIT license

Install

npm i @jest/environment
yarn add @jest/environment
pnpm add @jest/environment

Overview

Overview not available.

Index

Classes

class JestEnvironment

class JestEnvironment<Timer = unknown> {}

    constructor

    constructor(config: JestEnvironmentConfig, context: EnvironmentContext);

      property exportConditions

      exportConditions?: () => Array<string>;

        property fakeTimers

        fakeTimers: any;

          property fakeTimersModern

          fakeTimersModern: any;

            property global

            global: Global.Global;

              property handleTestEvent

              handleTestEvent?: Circus.EventHandler;

                property moduleMocker

                moduleMocker: any;

                  method getVmContext

                  getVmContext: () => Context | null;

                    method setup

                    setup: () => Promise<void>;

                      method teardown

                      teardown: () => Promise<void>;

                        Interfaces

                        interface Jest

                        interface Jest {}

                          property fn

                          fn: ModuleMocker['fn'];
                          • Creates a mock function. Optionally takes a mock implementation.

                          property isMockFunction

                          isMockFunction: ModuleMocker['isMockFunction'];
                          • Determines if the given function is a mocked function.

                          property mocked

                          mocked: ModuleMocker['mocked'];
                          • Wraps an object or a module with mock type definitions.

                          property requireActual

                          requireActual: (moduleName: string) => unknown;
                          • Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.

                            Example 1

                            ```js jest.mock('../myModule', () => { // Require the original module to not be mocked... const originalModule = jest.requireActual('../myModule');

                            return { __esModule: true, // Use it when dealing with esModules ...originalModule, getRandom: jest.fn().mockReturnValue(10), }; });

                            const getRandom = require('../myModule').getRandom;

                            getRandom(); // Always returns 10 ```

                          property requireMock

                          requireMock: (moduleName: string) => unknown;
                          • Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.

                          property spyOn

                          spyOn: ModuleMocker['spyOn'];
                          • Creates a mock function similar to jest.fn() but also tracks calls to object[methodName].

                            Optional third argument of accessType can be either 'get' or 'set', which proves to be useful when you want to spy on a getter or a setter, respectively.

                            Remarks

                            By default, jest.spyOn() also calls the spied method. This is different behavior from most other test libraries.

                          method advanceTimersByTime

                          advanceTimersByTime: (msToRun: number) => void;
                          • Advances all timers by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed within this time frame will be executed.

                          method advanceTimersToNextTimer

                          advanceTimersToNextTimer: (steps?: number) => void;
                          • Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run. Optionally, you can provide steps, so it will run steps amount of next timeouts/intervals.

                          method autoMockOff

                          autoMockOff: () => Jest;
                          • Disables automatic mocking in the module loader.

                          method autoMockOn

                          autoMockOn: () => Jest;
                          • Enables automatic mocking in the module loader.

                          method clearAllMocks

                          clearAllMocks: () => Jest;
                          • Clears the mock.calls, mock.instances, mock.contexts and mock.results properties of all mocks. Equivalent to calling .mockClear() on every mocked function.

                          method clearAllTimers

                          clearAllTimers: () => void;
                          • Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future.

                          method createMockFromModule

                          createMockFromModule: (moduleName: string) => unknown;
                          • Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.

                            This is useful when you want to create a manual mock that extends the automatic mock's behavior.

                          method deepUnmock

                          deepUnmock: (moduleName: string) => Jest;
                          • Indicates that the module system should never return a mocked version of the specified module and its dependencies.

                          method disableAutomock

                          disableAutomock: () => Jest;
                          • Disables automatic mocking in the module loader.

                            After this method is called, all require()s will return the real versions of each module (rather than a mocked version).

                          method doMock

                          doMock: (
                          moduleName: string,
                          moduleFactory?: () => unknown,
                          options?: { virtual?: boolean }
                          ) => Jest;
                          • When using babel-jest, calls to jest.mock() will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

                          method dontMock

                          dontMock: (moduleName: string) => Jest;
                          • When using babel-jest, calls to jest.unmock() will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior.

                          method enableAutomock

                          enableAutomock: () => Jest;
                          • Enables automatic mocking in the module loader.

                          method genMockFromModule

                          genMockFromModule: (moduleName: string) => unknown;
                          • Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you.

                            This is useful when you want to create a manual mock that extends the automatic mock's behavior.

                            Deprecated

                            Use jest.createMockFromModule() instead

                          method getRealSystemTime

                          getRealSystemTime: () => number;
                          • 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.

                            Remarks

                            Not available when using legacy fake timers implementation.

                          method getTimerCount

                          getTimerCount: () => number;
                          • Returns the number of fake timers still left to run.

                          method isolateModules

                          isolateModules: (fn: () => void) => Jest;
                          • jest.isolateModules() goes a step further than jest.resetModules() and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests.

                          method mock

                          mock: (
                          moduleName: string,
                          moduleFactory?: () => unknown,
                          options?: { virtual?: boolean }
                          ) => Jest;
                          • Mocks a module with an auto-mocked version when it is being required.

                          method resetAllMocks

                          resetAllMocks: () => Jest;
                          • Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.

                          method resetModules

                          resetModules: () => Jest;
                          • Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.

                          method restoreAllMocks

                          restoreAllMocks: () => Jest;
                          • Restores all mocks back to their original value. Equivalent to calling .mockRestore() on every mocked function.

                            Beware that jest.restoreAllMocks() only works when the mock was created with jest.spyOn(); other mocks will require you to manually restore them.

                          method retryTimes

                          retryTimes: (
                          numRetries: number,
                          options?: { logErrorsBeforeRetry?: boolean }
                          ) => Jest;
                          • Runs failed tests n-times until they pass or until the max number of retries is exhausted.

                            If logErrorsBeforeRetry is enabled, Jest will log the error(s) that caused the test to fail to the console, providing visibility on why a retry occurred. retries is exhausted.

                            Remarks

                            Only available with jest-circus runner.

                          method runAllImmediates

                          runAllImmediates: () => void;
                          • Exhausts tasks queued by setImmediate().

                            Remarks

                            Only available when using legacy fake timers implementation.

                          method runAllTicks

                          runAllTicks: () => void;
                          • Exhausts the micro-task queue (usually interfaced in node via process.nextTick()).

                          method runAllTimers

                          runAllTimers: () => void;
                          • Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()).

                          method runOnlyPendingTimers

                          runOnlyPendingTimers: () => void;
                          • Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call.

                          method setMock

                          setMock: (moduleName: string, moduleExports: unknown) => Jest;
                          • Explicitly supplies the mock object that the module system should return for the specified module.

                            Remarks

                            It is recommended to use jest.mock() instead. The jest.mock() API's second argument is a module factory instead of the expected exported module object.

                          method setSystemTime

                          setSystemTime: (now?: number | Date) => void;
                          • 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().

                            Remarks

                            Not available when using legacy fake timers implementation.

                          method setTimeout

                          setTimeout: (timeout: number) => Jest;
                          • Set the default timeout interval for tests and before/after hooks in milliseconds.

                            Remarks

                            The default timeout interval is 5 seconds if this method is not called.

                          method unmock

                          unmock: (moduleName: string) => Jest;
                          • Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module).

                          method unstable_mockModule

                          unstable_mockModule: <T = unknown>(
                          moduleName: string,
                          moduleFactory: () => Promise<T> | T,
                          options?: { virtual?: boolean }
                          ) => Jest;
                          • Mocks a module with the provided module factory when it is being imported.

                          method useFakeTimers

                          useFakeTimers: (
                          fakeTimersConfig?: Config.FakeTimersConfig | Config.LegacyFakeTimersConfig
                          ) => Jest;
                          • Instructs Jest to use fake versions of the global date, performance, time and timer APIs. Fake timers implementation is backed by [@sinonjs/fake-timers](https://github.com/sinonjs/fake-timers).

                            Remarks

                            Calling jest.useFakeTimers() once again in the same test file would reinstall fake timers using the provided options.

                          method useRealTimers

                          useRealTimers: () => Jest;
                          • Instructs Jest to restore the original implementations of the global date, performance, time and timer APIs.

                          interface JestEnvironmentConfig

                          interface JestEnvironmentConfig {}

                            property globalConfig

                            globalConfig: Config.GlobalConfig;

                              property projectConfig

                              projectConfig: Config.ProjectConfig;

                                interface JestImportMeta

                                interface JestImportMeta extends ImportMeta {}

                                  property jest

                                  jest: Jest;

                                    Type Aliases

                                    type EnvironmentContext

                                    type EnvironmentContext = {
                                    console: Console;
                                    docblockPragmas: Record<string, string | Array<string>>;
                                    testPath: string;
                                    };

                                      type Module

                                      type Module = NodeModule;

                                        type ModuleWrapper

                                        type ModuleWrapper = (
                                        this: Module['exports'],
                                        module: Module,
                                        exports: Module['exports'],
                                        require: Module['require'],
                                        __dirname: string,
                                        __filename: Module['filename'],
                                        jest?: Jest,
                                        ...sandboxInjectedGlobals: Array<Global.Global[keyof Global.Global]>
                                        ) => unknown;

                                          Package Files (1)

                                          Dependencies (4)

                                          Dev Dependencies (0)

                                          No dev dependencies.

                                          Peer Dependencies (0)

                                          No peer dependencies.

                                          Badge

                                          To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                          You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@jest/environment.

                                          • Markdown
                                            [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@jest/environment)
                                          • HTML
                                            <a href="https://www.jsdocs.io/package/@jest/environment"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>