Options
All
  • Public
  • Public/Protected
  • All
Menu

Module jest

Index

Type aliases

AndNot

AndNot<T>: T & { not: T }

Type parameters

  • T

ArgsType

ArgsType<T>: T extends (...args: infer A) => any ? A : never

Type parameters

  • T

CustomAsymmetricMatcher

CustomAsymmetricMatcher<TMatcher>: (...args: RemoveFirstFromTuple<Parameters<TMatcher>>) => AsymmetricMatcher

Type parameters

  • TMatcher: (...args: any[]) => any

Type declaration

CustomAsyncMatchers

CustomAsyncMatchers<TMatchers>: {}

Type parameters

Type declaration

CustomJestMatcher

CustomJestMatcher<TMatcher, TMatcherReturn>: (...args: RemoveFirstFromTuple<Parameters<TMatcher>>) => TMatcherReturn

Type parameters

  • TMatcher: (...args: any[]) => any

  • TMatcherReturn

Type declaration

CustomMatcher

CustomMatcher: (this: MatcherContext, received: any, ...actual: any[]) => CustomMatcherResult | Promise<CustomMatcherResult>

Type declaration

EmptyFunction

EmptyFunction: () => void

Type declaration

    • (): void
    • Returns void

EqualityTester

EqualityTester: (a: any, b: any) => boolean | undefined

Type declaration

    • (a: any, b: any): boolean | undefined
    • Parameters

      • a: any
      • b: any

      Returns boolean | undefined

ExpectProperties

ExpectProperties: {}

Type declaration

ExtendedExpect

ExtendedExpect<TMatchers>: ExpectProperties & AndNot<CustomAsyncMatchers<TMatchers>> & ExtendedExpectFunction<TMatchers>

Type parameters

ExtendedExpectFunction

ExtendedExpectFunction<TMatchers>: <TActual>(actual: TActual) => JestExtendedMatchers<TMatchers, TActual>

Type parameters

Type declaration

ExtendedMatchers

ExtendedMatchers<TMatchers, TMatcherReturn, TActual>: Matchers<TMatcherReturn, TActual> & {}

Type parameters

FunctionPropertyNames

FunctionPropertyNames<T>: {}[keyof T] & string

Type parameters

  • T

JestExtendedMatchers

JestExtendedMatchers<TMatchers, TActual>: JestMatchersShape<ExtendedMatchers<TMatchers, void, TActual>, ExtendedMatchers<TMatchers, Promise<void>, TActual>>

Type parameters

JestMatchers

JestMatchers<T>: JestMatchersShape<Matchers<void, T>, Matchers<Promise<void>, T>>

Type parameters

  • T

JestMatchersShape

JestMatchersShape<TNonPromise, TPromise>: { rejects: AndNot<TPromise>; resolves: AndNot<TPromise> } & AndNot<TNonPromise>

Type parameters

  • TNonPromise: {}

  • TPromise: {}

Lifecycle

Lifecycle: (fn: ProvidesCallback, timeout?: undefined | number) => any

Type declaration

MatcherColorFn

MatcherColorFn: ChalkFunction & { supportsColor: ChalkColorSupport }

MatcherContext

MatcherHintColor

MatcherHintColor: (arg: string) => string

Type declaration

    • (arg: string): string
    • Parameters

      • arg: string

      Returns string

MockResult

Type parameters

  • T

Mocked

Mocked<T>: {} & T

Wrap an object or a module with mock definitions

example

jest.mock("../api"); import * as api from "../api";

const mockApi = api as jest.Mocked; api.MyApi.prototype.myApiMethod.mockImplementation(() => "test");

Type parameters

  • T

MockedClass

MockedClass<T>: MockInstance<InstanceType<T>, T extends {} ? P : never> & { prototype: T extends { prototype: any } ? Mocked<T["prototype"]> : never } & T

Wrap a class with mock definitions

example

import { MyClass } from "./libary"; jest.mock("./library");

const mockedMyClass = MyClass as jest.MockedClass;

expect(mockedMyClass.mock.calls[0][0]).toBe(42); // Constructor calls expect(mockedMyClass.prototype.myMethod.mock.calls[0][0]).toBe(42); // Method calls

Type parameters

MockedFunction

MockedFunction<T>: MockInstance<ReturnType<T>, ArgsType<T>> & T

Wrap a function with mock definitions

example

import { myFunction } from "./library"; jest.mock("./library");

const mockMyFunction = myFunction as jest.MockedFunction; expect(mockMyFunction.mock.calls[0][0]).toBe(42);

Type parameters

  • T: (...args: any[]) => any

NonAsyncMatchers

NonAsyncMatchers<TMatchers>: {}[keyof TMatchers]

Type parameters

NonFunctionPropertyNames

NonFunctionPropertyNames<T>: {}[keyof T] & string

Type parameters

  • T

NonPromiseMatchers

NonPromiseMatchers<T>: Omit<T, "resolves" | "rejects" | "not">

Type parameters

Omit

Omit<T, K>: Pick<T, Exclude<keyof T, K>>

Construct a type with the properties of T except for those in type K.

Type parameters

  • T

  • K: keyof any

Parameters

Parameters<T>: T extends (...args: infer P) => any ? P : never

Type parameters

  • T: (...args: any[]) => any

PrintLabel

PrintLabel: (string: string) => string

Type declaration

    • (string: string): string
    • Parameters

      • string: string

      Returns string

PromiseMatchers

PromiseMatchers<T>: Omit<T["resolves"], "not">

Type parameters

ProvidesCallback

ProvidesCallback: (cb: DoneCallback) => any

Type declaration

RejectedValue

RejectedValue<T>: T extends PromiseLike<any> ? any : never

Type parameters

  • T

RemoveFirstFromTuple

RemoveFirstFromTuple<T>:

Type parameters

  • T: any[]

ResolvedValue

ResolvedValue<T>: T extends PromiseLike<infer U> ? U | T : never

Type parameters

  • T

SnapshotSerializerPlugin

SnapshotSerializerPlugin: { serialize: (val: any, config: Config, indentation: string, depth: number, refs: Refs, printer: Printer) => string; test: Test } | { print: (val: any, print: Print, indent: Indent, options: PluginOptions, colors: Colors) => string; test: Test }

Functions

addMatchers

  • Provides a way to add Jasmine-compatible matchers into your Jest context.

    Parameters

    Returns typeof jest

advanceTimersByTime

  • advanceTimersByTime(msToRun: number): typeof jest
  • Advances all timers by msToRun milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed within this timeframe will be executed.

    Parameters

    • msToRun: number

    Returns typeof jest

advanceTimersToNextTimer

  • advanceTimersToNextTimer(step?: undefined | 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.

    Parameters

    • Optional step: undefined | number

    Returns void

autoMockOff

  • autoMockOff(): typeof jest
  • Disables automatic mocking in the module loader.

    Returns typeof jest

autoMockOn

  • autoMockOn(): typeof jest
  • Enables automatic mocking in the module loader.

    Returns typeof jest

clearAllMocks

  • clearAllMocks(): typeof jest
  • Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.

    Returns typeof jest

clearAllTimers

  • clearAllTimers(): typeof jest
  • 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.

    Returns typeof jest

deepUnmock

  • deepUnmock(moduleName: string): typeof jest
  • Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies.

    Parameters

    • moduleName: string

    Returns typeof jest

disableAutomock

  • disableAutomock(): typeof jest
  • Disables automatic mocking in the module loader.

    Returns typeof jest

doMock

  • doMock(moduleName: string, factory?: undefined | (() => unknown), options?: MockOptions): typeof jest
  • Mocks a module with an auto-mocked version when it is being required.

    Parameters

    • moduleName: string
    • Optional factory: undefined | (() => unknown)
    • Optional options: MockOptions

    Returns typeof jest

dontMock

  • dontMock(moduleName: string): typeof 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).

    Parameters

    • moduleName: string

    Returns typeof jest

enableAutomock

  • enableAutomock(): typeof jest
  • Enables automatic mocking in the module loader.

    Returns typeof jest

fn

  • fn(): Mock
  • fn<T, Y>(implementation?: undefined | ((...args: Y) => T)): Mock<T, Y>
  • Creates a mock function. Optionally takes a mock implementation.

    Returns Mock

  • Creates a mock function. Optionally takes a mock implementation.

    Type parameters

    • T

    • Y: any[]

    Parameters

    • Optional implementation: undefined | ((...args: Y) => T)

    Returns Mock<T, Y>

genMockFromModule

  • genMockFromModule<T>(moduleName: string): T
  • Use the automatic mocking system to generate a mocked version of the given module.

    Type parameters

    • T

    Parameters

    • moduleName: string

    Returns T

getTimerCount

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

    Returns number

isMockFunction

  • isMockFunction(fn: any): fn is Mock
  • Returns whether the given function is a mock function.

    Parameters

    • fn: any

    Returns fn is Mock

isolateModules

  • isolateModules(fn: () => void): typeof jest
  • 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.

    Parameters

    • fn: () => void
        • (): void
        • Returns void

    Returns typeof jest

mock

  • mock(moduleName: string, factory?: undefined | (() => unknown), options?: MockOptions): typeof jest
  • Mocks a module with an auto-mocked version when it is being required.

    Parameters

    • moduleName: string
    • Optional factory: undefined | (() => unknown)
    • Optional options: MockOptions

    Returns typeof jest

requireActual

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

    Parameters

    • moduleName: string

    Returns any

requireMock

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

    Parameters

    • moduleName: string

    Returns any

resetAllMocks

  • resetAllMocks(): typeof jest
  • Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.

    Returns typeof jest

resetModuleRegistry

  • resetModuleRegistry(): typeof jest
  • Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests.

    Returns typeof jest

resetModules

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

    Returns typeof jest

restoreAllMocks

  • restoreAllMocks(): typeof jest
  • available since Jest 21.1.0 Restores all mocks back to their original value. Equivalent to calling .mockRestore on every mocked function. Beware that jest.restoreAllMocks() only works when mock was created with jest.spyOn; other mocks will require you to manually restore them.

    Returns typeof jest

retryTimes

  • retryTimes(numRetries: number): typeof jest
  • Runs failed tests n-times until they pass or until the max number of retries is exhausted. This only works with jest-circus!

    Parameters

    • numRetries: number

    Returns typeof jest

runAllImmediates

  • runAllImmediates(): typeof jest
  • Exhausts tasks queued by setImmediate().

    Returns typeof jest

runAllTicks

  • runAllTicks(): typeof jest
  • Exhausts the micro-task queue (usually interfaced in node via process.nextTick).

    Returns typeof jest

runAllTimers

  • runAllTimers(): typeof jest
  • Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()).

    Returns typeof jest

runOnlyPendingTimers

  • runOnlyPendingTimers(): typeof jest
  • 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.

    Returns typeof jest

runTimersToTime

  • runTimersToTime(msToRun: number): typeof jest
  • (renamed to advanceTimersByTime in Jest 21.3.0+) Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()).

    Parameters

    • msToRun: number

    Returns typeof jest

setMock

  • setMock<T>(moduleName: string, moduleExports: T): typeof jest
  • Explicitly supplies the mock object that the module system should return for the specified module.

    Type parameters

    • T

    Parameters

    • moduleName: string
    • moduleExports: T

    Returns typeof jest

setTimeout

  • setTimeout(timeout: number): typeof jest
  • Set the default timeout interval for tests and before/after hooks in milliseconds. Note: The default timeout interval is 5 seconds if this method is not called.

    Parameters

    • timeout: number

    Returns typeof jest

spyOn

  • spyOn<T, M>(object: T, method: M, accessType: "get"): SpyInstance<Required<T>[M], []>
  • spyOn<T, M>(object: T, method: M, accessType: "set"): SpyInstance<void, [Required<T>[M]]>
  • spyOn<T, M>(object: T, method: M): Required<T>[M] extends (...args: any[]) => any ? SpyInstance<ReturnType<Required<T>[M]>, ArgsType<Required<T>[M]>> : never
  • Creates a mock function similar to jest.fn but also tracks calls to object[methodName]

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

    example

    const video = require('./video');

    test('plays video', () => { const spy = jest.spyOn(video, 'play'); const isPlaying = video.play();

    expect(spy).toHaveBeenCalled(); expect(isPlaying).toBe(true);

    spy.mockReset(); spy.mockRestore(); });

    Type parameters

    Parameters

    • object: T
    • method: M
    • accessType: "get"

    Returns SpyInstance<Required<T>[M], []>

  • Type parameters

    Parameters

    • object: T
    • method: M
    • accessType: "set"

    Returns SpyInstance<void, [Required<T>[M]]>

  • Type parameters

    Parameters

    • object: T
    • method: M

    Returns Required<T>[M] extends (...args: any[]) => any ? SpyInstance<ReturnType<Required<T>[M]>, ArgsType<Required<T>[M]>> : never

unmock

  • unmock(moduleName: string): typeof 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).

    Parameters

    • moduleName: string

    Returns typeof jest

useFakeTimers

  • useFakeTimers(): typeof jest
  • Instructs Jest to use fake versions of the standard timer functions.

    Returns typeof jest

useRealTimers

  • useRealTimers(): typeof jest
  • Instructs Jest to use the real versions of the standard timer functions.

    Returns typeof jest