@types/jest
- Version 29.5.14
- Published
- 78.8 kB
- 2 dependencies
- MIT license
Install
npm i @types/jest
yarn add @types/jest
pnpm add @types/jest
Overview
TypeScript definitions for jest
Index
Variables
Functions
Namespaces
jasmine
- addCustomEqualityTester()
- any()
- Any
- anything()
- arrayContaining()
- ArrayContaining
- ArrayLike
- CallInfo
- Calls
- clock()
- Clock
- createSpy()
- createSpyObj()
- CustomEqualityTester
- CustomMatcher
- CustomMatcherFactories
- CustomMatcherFactory
- CustomMatcherResult
- DEFAULT_TIMEOUT_INTERVAL
- MatchersUtil
- objectContaining()
- ObjectContaining
- pp()
- Spy
- SpyAnd
- stringMatching()
jest
- advanceTimersByTime()
- advanceTimersByTimeAsync()
- advanceTimersToNextTimer()
- advanceTimersToNextTimerAsync()
- AndNot
- ArgsType
- ArgumentsOf
- AsymmetricMatcher
- autoMockOff()
- autoMockOn()
- clearAllMocks()
- clearAllTimers()
- Constructable
- Constructor
- ConstructorArgsType
- ConstructorArgumentsOf
- ConstructorProperties
- ConstructorPropertyNames
- ConstructorReturnType
- createMockFromModule()
- CustomAsymmetricMatcher
- CustomAsyncMatchers
- CustomJestMatcher
- CustomMatcher
- CustomMatcherResult
- deepUnmock()
- Describe
- disableAutomock()
- doMock()
- DoneCallback
- dontMock()
- Each
- EmptyFunction
- enableAutomock()
- EqualityTester
- Expect
- ExpectExtendMap
- ExpectProperties
- ExtendedExpect
- ExtendedExpectFunction
- ExtendedMatchers
- fn()
- Func
- FunctionLike
- FunctionProperties
- FunctionPropertyNames
- genMockFromModule()
- GetAccessor
- getRealSystemTime()
- getSeed()
- getTimerCount()
- InverseAsymmetricMatchers
- isEnvironmentTornDown()
- isMockFunction()
- isolateModules()
- isolateModulesAsync()
- It
- JestExtendedMatchers
- JestMatchers
- JestMatchersShape
- Lifecycle
- MatcherContext
- Matchers
- MatcherState
- MatcherUtils
- MaybeMocked
- MaybeMockedConstructor
- MaybeMockedDeep
- MethodKeysOf
- mock()
- Mock
- MockableFunction
- MockContext
- mocked()
- Mocked
- MockedClass
- MockedFn
- MockedFunction
- MockedFunctionDeep
- MockedObject
- MockedObjectDeep
- MockInstance
- MockOptions
- MockResult
- MockResultIncomplete
- MockResultReturn
- MockResultThrow
- MockWithArgs
- NonAsyncMatchers
- NonFunctionPropertyNames
- NonPromiseMatchers
- now()
- PromiseMatchers
- PropertyAccessors
- PropertyKeysOf
- ProvidesCallback
- ProvidesHookCallback
- RejectedValue
- RemoveFirstFromTuple
- RemoveIndex
- replaceProperty()
- ReplaceProperty
- requireActual()
- requireMock()
- resetAllMocks()
- resetModules()
- ResolvedValue
- restoreAllMocks()
- retryTimes()
- runAllImmediates()
- runAllTicks()
- runAllTimers()
- runAllTimersAsync()
- runOnlyPendingTimers()
- runOnlyPendingTimersAsync()
- SetAccessor
- setMock()
- setSystemTime()
- setTimeout()
- SnapshotSerializerPlugin
- Spied
- SpiedClass
- SpiedFunction
- SpiedGetter
- SpiedSetter
- SpyInstance
- spyOn()
- unmock()
- useFakeTimers()
- useRealTimers()
Variables
variable afterAll
var afterAll: jest.Lifecycle;
variable afterEach
var afterEach: jest.Lifecycle;
variable beforeAll
var beforeAll: jest.Lifecycle;
variable beforeEach
var beforeEach: jest.Lifecycle;
variable describe
var describe: jest.Describe;
variable expect
const expect: jest.Expect;
variable fdescribe
var fdescribe: jest.Describe;
variable fit
var fit: jest.It;
variable it
var it: jest.It;
variable test
var test: jest.It;
variable xdescribe
var xdescribe: jest.Describe;
variable xit
var xit: jest.It;
variable xtest
var xtest: jest.It;
Functions
function fail
fail: (error?: any) => never;
Fails a test when called within one.
function pending
pending: (reason?: string) => void;
If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending.
function spyOn
spyOn: <T>(object: T, method: keyof T) => jasmine.Spy;
Namespaces
namespace jasmine
namespace jasmine {}
variable DEFAULT_TIMEOUT_INTERVAL
let DEFAULT_TIMEOUT_INTERVAL: number;
function addCustomEqualityTester
addCustomEqualityTester: (equalityTester: CustomEqualityTester) => void;
function any
any: (aclass: any) => Any;
function anything
anything: () => Any;
function arrayContaining
arrayContaining: (sample: readonly any[]) => ArrayContaining;
function clock
clock: () => Clock;
function createSpy
createSpy: (name?: string, originalFn?: (...args: any[]) => any) => Spy;
function createSpyObj
createSpyObj: { (baseName: string, methodNames: any[]): any; <T>(baseName: string, methodNames: any[]): T;};
function objectContaining
objectContaining: (sample: any) => ObjectContaining;
function pp
pp: (value: any) => string;
function stringMatching
stringMatching: (value: string | RegExp) => Any;
interface Any
interface Any {}
method jasmineMatches
jasmineMatches: (other: any) => boolean;
method jasmineToString
jasmineToString: () => string;
construct signature
new (expectedClass: any): any;
interface ArrayContaining
interface ArrayContaining {}
method asymmetricMatch
asymmetricMatch: (other: any) => boolean;
method jasmineToString
jasmineToString: () => string;
construct signature
new (sample: readonly any[]): any;
interface ArrayLike
interface ArrayLike<T> {}
property length
length: number;
index signature
[n: number]: T;
interface CallInfo
interface CallInfo {}
property args
args: any[];
All arguments passed to the call
property object
object: any;
The context (the this) for the call
property returnValue
returnValue: any;
The return value of the call
interface Calls
interface Calls {}
method all
all: () => CallInfo[];
By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls
method allArgs
allArgs: () => any[];
By chaining the spy with calls.allArgs(), will return the arguments to all calls
method any
any: () => boolean;
By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens.
method argsFor
argsFor: (index: number) => any[];
By chaining the spy with calls.argsFor(), will return the arguments passed to call number index
method count
count: () => number;
By chaining the spy with calls.count(), will return the number of times the spy was called
method first
first: () => CallInfo;
By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call
method mostRecent
mostRecent: () => CallInfo;
By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call
method reset
reset: () => void;
By chaining the spy with calls.reset(), will clears all tracking for a spy
interface Clock
interface Clock {}
method install
install: () => void;
method mockDate
mockDate: (date?: Date) => void;
method tick
tick: (ms: number) => void;
Calls to any registered callback are triggered when the clock isticked forward via the jasmine.clock().tick function, which takes a number of milliseconds.
method uninstall
uninstall: () => void;
interface CustomMatcher
interface CustomMatcher {}
method compare
compare: { <T>(actual: T, expected: T, ...args: any[]): CustomMatcherResult; (actual: any, ...expected: any[]): CustomMatcherResult;};
interface CustomMatcherFactories
interface CustomMatcherFactories {}
index signature
[index: string]: CustomMatcherFactory;
interface CustomMatcherResult
interface CustomMatcherResult {}
interface MatchersUtil
interface MatchersUtil {}
method buildFailureMessage
buildFailureMessage: ( matcherName: string, isNot: boolean, actual: any, ...expected: any[]) => string;
method contains
contains: <T>( haystack: ArrayLike<T> | string, needle: any, customTesters?: CustomEqualityTester[]) => boolean;
method equals
equals: (a: any, b: any, customTesters?: CustomEqualityTester[]) => boolean;
interface ObjectContaining
interface ObjectContaining {}
method jasmineMatches
jasmineMatches: ( other: any, mismatchKeys: any[], mismatchValues: any[]) => boolean;
method jasmineToString
jasmineToString: () => string;
construct signature
new (sample: any): any;
interface Spy
interface Spy {}
property and
and: SpyAnd;
property argsForCall
argsForCall: any[];
property calls
calls: Calls;
property identity
identity: string;
property mostRecentCall
mostRecentCall: { args: any[] };
property wasCalled
wasCalled: boolean;
call signature
(...params: any[]): any;
interface SpyAnd
interface SpyAnd {}
method callFake
callFake: (fn: (...args: any[]) => any) => Spy;
By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function.
method callThrough
callThrough: () => Spy;
By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation.
method returnValue
returnValue: (val: any) => Spy;
By chaining the spy with and.returnValue, all calls to the function will return a specific value.
method returnValues
returnValues: (...values: any[]) => Spy;
By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list.
method stub
stub: () => Spy;
When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub.
method throwError
throwError: (msg: string) => Spy;
By chaining the spy with and.throwError, all calls to the spy will throw the specified value.
type CustomEqualityTester
type CustomEqualityTester = (first: any, second: any) => boolean;
type CustomMatcherFactory
type CustomMatcherFactory = ( util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => CustomMatcher;
namespace jest
namespace jest {}
function advanceTimersByTime
advanceTimersByTime: (msToRun: number) => void;
Advances all timers by
msToRun
milliseconds. All pending macro-tasks that have been queued bysetTimeout()
,setInterval()
andsetImmediate()
, and would be executed within this time frame will be executed.
function advanceTimersByTimeAsync
advanceTimersByTimeAsync: (msToRun: number) => Promise<void>;
Asynchronous equivalent of
jest.advanceTimersByTime()
. It also yields to the event loop, allowing any scheduled promise callbacks to execute _before_ running the timers.Remarks
Not available when using legacy fake timers implementation.
function advanceTimersToNextTimer
advanceTimersToNextTimer: (step?: 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.
function advanceTimersToNextTimerAsync
advanceTimersToNextTimerAsync: (steps?: number) => Promise<void>;
Asynchronous equivalent of
jest.advanceTimersToNextTimer()
. It also yields to the event loop, allowing any scheduled promise callbacks to execute _before_ running the timers.Remarks
Not available when using legacy fake timers implementation.
function autoMockOff
autoMockOff: () => typeof jest;
Disables automatic mocking in the module loader.
function autoMockOn
autoMockOn: () => typeof jest;
Enables automatic mocking in the module loader.
function clearAllMocks
clearAllMocks: () => typeof jest;
Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function.
function 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.
function createMockFromModule
createMockFromModule: <T>(moduleName: string) => T;
Use the automatic mocking system to generate a mocked version of the given module.
function 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 specified module's dependencies.
function disableAutomock
disableAutomock: () => typeof jest;
Disables automatic mocking in the module loader.
function doMock
doMock: <T = unknown>( moduleName: string, factory?: () => T, options?: MockOptions) => typeof jest;
Mocks a module with an auto-mocked version when it is being required.
function 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).
function enableAutomock
enableAutomock: () => typeof jest;
Enables automatic mocking in the module loader.
function fn
fn: { (): Mock; <T, Y extends any[], C = any>(implementation?: (this: C, ...args: Y) => T): Mock< T, Y, C >;};
Creates a mock function. Optionally takes a mock implementation.
function genMockFromModule
genMockFromModule: <T>(moduleName: string) => T;
(renamed to
createMockFromModule
in Jest 26.0.0+) Use the automatic mocking system to generate a mocked version of the given module.
function 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.
> Note: This function is only available when using modern fake timers > implementation
function getSeed
getSeed: () => number;
Retrieves the seed value. It will be randomly generated for each test run or can be manually set via the
--seed
CLI argument.
function getTimerCount
getTimerCount: () => number;
Returns the number of fake timers still left to run.
function isEnvironmentTornDown
isEnvironmentTornDown: () => boolean;
Returns
true
if test environment has been torn down.Example 1
if (jest.isEnvironmentTornDown()) { // The Jest environment has been torn down, so stop doing work return; }
function isMockFunction
isMockFunction: (fn: any) => fn is Mock<any, any, any>;
Returns whether the given function is a mock function.
function 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.
function isolateModulesAsync
isolateModulesAsync: (fn: () => Promise<void>) => Promise<void>;
Equivalent of
jest.isolateModules()
for async functions to be wrapped. The caller is expected toawait
the completion ofjest.isolateModulesAsync()
.
function mock
mock: <T = unknown>( moduleName: string, factory?: () => T, options?: MockOptions) => typeof jest;
Mocks a module with an auto-mocked version when it is being required.
function mocked
mocked: { <T>(source: T, options?: { shallow: false }): MaybeMockedDeep<T>; <T>(source: T, options: { shallow: true }): MaybeMocked<T>;};
Wraps types of the
source
object and its deep members with type definitions of Jest mock function. Pass{shallow: true}
option to disable the deeply mocked behavior.Wraps types of the
source
object with type definitions of Jest mock function.
function now
now: () => number;
Returns the current time in ms of the fake timer clock.
function replaceProperty
replaceProperty: <T extends object, K extends keyof T>( obj: T, key: K, value: T[K]) => ReplaceProperty<T[K]>;
Replaces property on an object with another value.
Remarks
For mocking functions, and 'get' or 'set' accessors, use
jest.spyOn()
instead.
function requireActual
requireActual: <TModule extends {} = any>(moduleName: string) => TModule;
Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not.
function requireMock
requireMock: <TModule extends {} = any>(moduleName: string) => TModule;
Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not.
function resetAllMocks
resetAllMocks: () => typeof jest;
Resets the state of all mocks. Equivalent to calling .mockReset() on every mocked function.
function 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.
function restoreAllMocks
restoreAllMocks: () => typeof jest;
Restores all mocks and replaced properties back to their original value. Equivalent to calling
.mockRestore()
on every mocked function and.restore()
on every replaced property.Beware that
jest.restoreAllMocks()
only works when the mock was created withjest.spyOn()
; other mocks will require you to manually restore them.
function retryTimes
retryTimes: ( numRetries: number, options?: { logErrorsBeforeRetry?: boolean }) => 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!
function runAllImmediates
runAllImmediates: () => void;
Exhausts tasks queued by
setImmediate()
.Remarks
This function is only available when using legacy fake timers implementation.
function runAllTicks
runAllTicks: () => void;
Exhausts the micro-task queue (i.e., tasks in Node.js scheduled with
process.nextTick()
).
function runAllTimers
runAllTimers: () => void;
Exhausts both the macro-task queue (i.e., tasks queued by
setTimeout()
,setInterval()
andsetImmediate()
) and the micro-task queue (i.e., tasks in Node.js scheduled withprocess.nextTick()
).
function runAllTimersAsync
runAllTimersAsync: () => Promise<void>;
Asynchronous equivalent of
jest.runAllTimers()
. It also yields to the event loop, allowing any scheduled promise callbacks to execute _before_ running the timers.Remarks
Not available when using legacy fake timers implementation.
function runOnlyPendingTimers
runOnlyPendingTimers: () => void;
Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by
setTimeout()
,setInterval()
andsetImmediate()
up to this point).
function runOnlyPendingTimersAsync
runOnlyPendingTimersAsync: () => Promise<void>;
Asynchronous equivalent of
jest.runOnlyPendingTimers()
. It also yields to the event loop, allowing any scheduled promise callbacks to execute _before_ running the timers.Remarks
Not available when using legacy fake timers implementation.
function setMock
setMock: <T>(moduleName: string, moduleExports: T) => typeof jest;
Explicitly supplies the mock object that the module system should return for the specified module.
function 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().
> Note: This function is only available when using modern fake timers > implementation
function 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.
function spyOn
spyOn: { < T extends {}, Key extends keyof T, A extends PropertyAccessors<Key, T> = PropertyAccessors<Key, T>, Value extends Required<T>[Key] = Required<T>[Key] >( object: T, method: Key, accessType: A ): A extends SetAccessor ? SpyInstance<void, [Value]> : A extends GetAccessor ? SpyInstance<Value, []> : Value extends Constructor ? SpyInstance<InstanceType<Value>, ConstructorArgsType<Value>> : Value extends Func ? SpyInstance<ReturnType<Value>, ArgsType<Value>> : never; <T extends {}, M extends keyof ConstructorProperties<Required<T>>>( object: T, method: M ): ConstructorProperties<Required<T>>[M] extends new (...args: any[]) => any ? SpyInstance< InstanceType<ConstructorProperties<Required<T>>[M]>, ConstructorArgsType<ConstructorProperties<Required<T>>[M]>, any > : never; <T extends {}, M extends keyof FunctionProperties<Required<T>>>( object: T, method: M ): FunctionProperties<Required<T>>[M] extends Func ? SpyInstance< ReturnType<FunctionProperties<Required<T>>[M]>, ArgsType<FunctionProperties<Required<T>>[M]>, any > : 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 1
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(); });
function 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).
function useFakeTimers
useFakeTimers: ( config?: FakeTimersConfig | LegacyFakeTimersConfig) => typeof jest;
Instructs Jest to use fake versions of the standard timer functions.
function useRealTimers
useRealTimers: () => typeof jest;
Instructs Jest to use the real versions of the standard timer functions.
interface AsymmetricMatcher
interface AsymmetricMatcher {}
method asymmetricMatch
asymmetricMatch: (other: unknown) => boolean;
interface Constructable
interface Constructable {}
construct signature
new (...args: any[]): any;
interface CustomMatcherResult
interface CustomMatcherResult {}
interface Describe
interface Describe {}
property each
each: Each;
property only
only: Describe;
Only runs the tests inside this
describe
for the current file
property skip
skip: Describe;
Skips running the tests inside this
describe
for the current file
call signature
(name: number | string | Function | FunctionLike, fn: EmptyFunction): void;
interface DoneCallback
interface DoneCallback {}
method fail
fail: (error?: string | { message: string }) => any;
call signature
(...args: any[]): any;
interface Each
interface Each {}
call signature
<T extends any[] | [any]>(cases: readonly T[]): ( name: string, fn: (...args: T) => any, timeout?: number) => void;
call signature
<T extends readonly any[]>(cases: readonly T[]): ( name: string, fn: (...args: ExtractEachCallbackArgs<T>) => any, timeout?: number) => void;
call signature
<T>(cases: readonly T[]): ( name: string, fn: (arg: T, done: DoneCallback) => any, timeout?: number) => void;
call signature
(cases: ReadonlyArray<readonly any[]>): ( name: string, fn: (...args: any[]) => any, timeout?: number) => void;
call signature
(strings: TemplateStringsArray, ...placeholders: any[]): ( name: string, fn: (arg: any, done: DoneCallback) => any, timeout?: number) => void;
interface Expect
interface Expect {}
The
expect
function is used every time you want to test a value. You will rarely callexpect
by itself.
property not
not: InverseAsymmetricMatchers;
method addSnapshotSerializer
addSnapshotSerializer: (serializer: any) => void;
Adds a module to format application-specific data structures for serialization.
method any
any: (classType: any) => any;
Matches anything that was created with the given constructor. You can use it inside
toEqual
ortoBeCalledWith
instead of a literal value.Example 1
function randocall(fn) { return fn(Math.floor(Math.random() * 6 + 1)); }
test('randocall calls its callback with a number', () => { const mock = jest.fn(); randocall(mock); expect(mock).toBeCalledWith(expect.any(Number)); });
method anything
anything: () => any;
Matches anything but null or undefined. You can use it inside
toEqual
ortoBeCalledWith
instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument:Example 1
test('map calls its argument with a non-null argument', () => { const mock = jest.fn(); [1].map(x => mock(x)); expect(mock).toBeCalledWith(expect.anything()); });
method arrayContaining
arrayContaining: <E = any>(arr: readonly E[]) => any;
Matches any array made up entirely of elements in the provided array. You can use it inside
toEqual
ortoBeCalledWith
instead of a literal value.Optionally, you can provide a type for the elements via a generic.
method assertions
assertions: (num: number) => void;
Verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
method closeTo
closeTo: (num: number, numDigits?: number) => any;
Useful when comparing floating point numbers in object properties or array item. If you need to compare a number, use
.toBeCloseTo
instead.The optional
numDigits
argument limits the number of digits to check after the decimal point. For the default value 2, the test criterion isMath.abs(expected - received) < 0.005
(that is,10 ** -2 / 2
).
method extend
extend: (obj: ExpectExtendMap) => void;
You can use
expect.extend
to add your own matchers to Jest.
method getState
getState: () => MatcherState & Record<string, any>;
method hasAssertions
hasAssertions: () => void;
Verifies that at least one assertion is called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.
method objectContaining
objectContaining: <E = {}>(obj: E) => any;
Matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers.
Optionally, you can provide a type for the object via a generic. This ensures that the object contains the desired structure.
method setState
setState: (state: object) => void;
method stringContaining
stringContaining: (str: string) => any;
Matches any received string that contains the exact expected string
method stringMatching
stringMatching: (str: string | RegExp) => any;
Matches any string that contains the exact provided string
call signature
<T = any>(actual: T): JestMatchers<T>;
The
expect
function is used every time you want to test a value. You will rarely callexpect
by itself.Parameter actual
The value to apply matchers against.
interface ExpectExtendMap
interface ExpectExtendMap {}
index signature
[key: string]: CustomMatcher;
interface FunctionLike
interface FunctionLike {}
property name
readonly name: string;
interface InverseAsymmetricMatchers
interface InverseAsymmetricMatchers {}
method arrayContaining
arrayContaining: <E = any>(arr: readonly E[]) => any;
expect.not.arrayContaining(array)
matches a received array which does not contain all of the elements in the expected array. That is, the expected array is not a subset of the received array. It is the inverse ofexpect.arrayContaining
.Optionally, you can provide a type for the elements via a generic.
method objectContaining
objectContaining: <E = {}>(obj: E) => any;
expect.not.objectContaining(object)
matches any received object that does not recursively match the expected properties. That is, the expected object is not a subset of the received object. Therefore, it matches a received object which contains properties that are not in the expected object. It is the inverse ofexpect.objectContaining
.Optionally, you can provide a type for the object via a generic. This ensures that the object contains the desired structure.
method stringContaining
stringContaining: (str: string) => any;
expect.not.stringContaining(string)
matches the received string that does not contain the exact expected string. It is the inverse ofexpect.stringContaining
.
method stringMatching
stringMatching: (str: string | RegExp) => any;
expect.not.stringMatching(string | regexp)
matches the received string that does not match the expected regexp. It is the inverse ofexpect.stringMatching
.
interface It
interface It {}
Creates a test closure
property concurrent
concurrent: It;
Experimental and should be avoided.
property each
each: Each;
Use if you keep duplicating the same test with different data.
.each
allows you to write the test once and pass data in..each
is available with two APIs:#### 1
test.each(table)(name, fn)
-
table
: Array of Arrays with the arguments that are passed into the test fn for each row. -name
: String the title of the test block. -fn
: Function the test to be run, this is the function that will receive the parameters in each row as function arguments.#### 2
test.each table(name, fn)
-
table
: Tagged Template Literal -name
: String the title of the test, use$variable
to inject test data into the test title from the tagged template expressions. -fn
: Function the test to be run, this is the function that will receive the test data object.Example 1
// API 1 test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( '.add(%i, %i)', (a, b, expected) => { expect(a + b).toBe(expected); }, );
// API 2 test.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `('returns $expected when $a is added $b', ({a, b, expected}) => { expect(a + b).toBe(expected); });
property failing
failing: It;
Mark this test as expecting to fail.
Only available in the default
jest-circus
runner.
property only
only: It;
Only runs this test in the current file.
property skip
skip: It;
Skips running this test in the current file.
property todo
todo: (name: string) => void;
Sketch out which tests to write in the future.
call signature
(name: string, fn?: ProvidesCallback, timeout?: number): void;
Creates a test closure.
Parameter name
The name of your test
Parameter fn
The function for your test
Parameter timeout
The timeout for an async function test
interface Matchers
interface Matchers<R, T = {}> {}
method lastCalledWith
lastCalledWith: <E extends any[]>(...args: E) => R;
Ensures the last call to a mock function was provided specific args.
Optionally, you can provide a type for the expected arguments via a generic. Note that the type must be either an array or a tuple.
Deprecated
in favor of
toHaveBeenLastCalledWith
method lastReturnedWith
lastReturnedWith: <E = any>(expected?: E) => R;
Ensure that the last call to a mock function has returned a specified value.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
Deprecated
in favor of
toHaveLastReturnedWith
method nthCalledWith
nthCalledWith: <E extends any[]>(nthCall: number, ...params: E) => R;
Ensure that a mock function is called with specific arguments on an Nth call.
Optionally, you can provide a type for the expected arguments via a generic. Note that the type must be either an array or a tuple.
Deprecated
in favor of
toHaveBeenNthCalledWith
method nthReturnedWith
nthReturnedWith: <E = any>(n: number, expected?: E) => R;
Ensure that the nth call to a mock function has returned a specified value.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
Deprecated
in favor of
toHaveNthReturnedWith
method toBe
toBe: <E = any>(expected: E) => R;
Checks that a value is what you expect. It uses
Object.is
to check strict equality. Don't usetoBe
with floating-point numbers.Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toBeCalled
toBeCalled: () => R;
Ensures that a mock function is called.
Deprecated
in favor of
toHaveBeenCalled
method toBeCalledTimes
toBeCalledTimes: (expected: number) => R;
Ensures that a mock function is called an exact number of times.
Deprecated
in favor of
toHaveBeenCalledTimes
method toBeCalledWith
toBeCalledWith: <E extends any[]>(...args: E) => R;
Ensure that a mock function is called with specific arguments.
Optionally, you can provide a type for the expected arguments via a generic. Note that the type must be either an array or a tuple.
Deprecated
in favor of
toHaveBeenCalledWith
method toBeCloseTo
toBeCloseTo: (expected: number, numDigits?: number) => R;
Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. The default for numDigits is 2.
method toBeDefined
toBeDefined: () => R;
Ensure that a variable is not undefined.
method toBeFalsy
toBeFalsy: () => R;
When you don't care what a value is, you just want to ensure a value is false in a boolean context.
method toBeGreaterThan
toBeGreaterThan: (expected: number | bigint) => R;
For comparing floating point or big integer numbers.
method toBeGreaterThanOrEqual
toBeGreaterThanOrEqual: (expected: number | bigint) => R;
For comparing floating point or big integer numbers.
method toBeInstanceOf
toBeInstanceOf: <E = any>(expected: E) => R;
Ensure that an object is an instance of a class. This matcher uses
instanceof
underneath.Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toBeLessThan
toBeLessThan: (expected: number | bigint) => R;
For comparing floating point or big integer numbers.
method toBeLessThanOrEqual
toBeLessThanOrEqual: (expected: number | bigint) => R;
For comparing floating point or big integer numbers.
method toBeNaN
toBeNaN: () => R;
Used to check that a variable is NaN.
method toBeNull
toBeNull: () => R;
This is the same as
.toBe(null)
but the error messages are a bit nicer. So use.toBeNull()
when you want to check that something is null.
method toBeTruthy
toBeTruthy: () => R;
Use when you don't care what a value is, you just want to ensure a value is true in a boolean context. In JavaScript, there are six falsy values:
false
,0
,''
,null
,undefined
, andNaN
. Everything else is truthy.
method toBeUndefined
toBeUndefined: () => R;
Used to check that a variable is undefined.
method toContain
toContain: <E = any>(expected: E) => R;
Used when you want to check that an item is in a list. For testing the items in the list, this uses
===
, a strict equality check. It can also check whether a string is a substring of another string.Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toContainEqual
toContainEqual: <E = any>(expected: E) => R;
Used when you want to check that an item is in a list. For testing the items in the list, this matcher recursively checks the equality of all fields, rather than checking for object identity.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toEqual
toEqual: <E = any>(expected: E) => R;
Used when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toHaveBeenCalled
toHaveBeenCalled: () => R;
Ensures that a mock function is called.
method toHaveBeenCalledTimes
toHaveBeenCalledTimes: (expected: number) => R;
Ensures that a mock function is called an exact number of times.
method toHaveBeenCalledWith
toHaveBeenCalledWith: <E extends any[]>(...params: E) => R;
Ensure that a mock function is called with specific arguments.
Optionally, you can provide a type for the expected arguments via a generic. Note that the type must be either an array or a tuple.
method toHaveBeenLastCalledWith
toHaveBeenLastCalledWith: <E extends any[]>(...params: E) => R;
If you have a mock function, you can use
.toHaveBeenLastCalledWith
to test what arguments it was last called with.Optionally, you can provide a type for the expected arguments via a generic. Note that the type must be either an array or a tuple.
method toHaveBeenNthCalledWith
toHaveBeenNthCalledWith: <E extends any[]>(nthCall: number, ...params: E) => R;
Ensure that a mock function is called with specific arguments on an Nth call.
Optionally, you can provide a type for the expected arguments via a generic. Note that the type must be either an array or a tuple.
method toHaveLastReturnedWith
toHaveLastReturnedWith: <E = any>(expected?: E) => R;
Use to test the specific value that a mock function last returned. If the last call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toHaveLength
toHaveLength: (expected: number) => R;
Used to check that an object has a
.length
property and it is set to a certain numeric value.
method toHaveNthReturnedWith
toHaveNthReturnedWith: <E = any>(nthCall: number, expected?: E) => R;
Use to test the specific value that a mock function returned for the nth call. If the nth call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toHaveProperty
toHaveProperty: <E = any>(propertyPath: string | readonly any[], value?: E) => R;
Use to check if property at provided reference keyPath exists for an object. For checking deeply nested properties in an object you may use dot notation or an array containing the keyPath for deep references.
Optionally, you can provide a value to check if it's equal to the value present at keyPath on the target object. This matcher uses 'deep equality' (like
toEqual()
) and recursively checks the equality of all fields.Example 1
expect(houseForSale).toHaveProperty('kitchen.area', 20);
method toHaveReturned
toHaveReturned: () => R;
Use to test that the mock function successfully returned (i.e., did not throw an error) at least one time
method toHaveReturnedTimes
toHaveReturnedTimes: (expected: number) => R;
Use to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. Any calls to the mock function that throw an error are not counted toward the number of times the function returned.
method toHaveReturnedWith
toHaveReturnedWith: <E = any>(expected?: E) => R;
Use to ensure that a mock function returned a specific value.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toMatch
toMatch: (expected: string | RegExp) => R;
Check that a string matches a regular expression.
method toMatchInlineSnapshot
toMatchInlineSnapshot: { <U extends { [P in keyof T]: any }>( propertyMatchers: Partial<U>, snapshot?: string ): R; (snapshot?: string): R;};
This ensures that a value matches the most recent snapshot with property matchers. Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
method toMatchObject
toMatchObject: <E extends {} | any[]>(expected: E) => R;
Used to check that a JavaScript object matches a subset of the properties of an object
Optionally, you can provide an object to use as Generic type for the expected value. This ensures that the matching object matches the structure of the provided object-like type.
Example 1
type House = { bath: boolean; bedrooms: number; kitchen: { amenities: string[]; area: number; wallColor: string; } };
expect(desiredHouse).toMatchObject({...standardHouse, kitchen: {area: 20}}) // wherein standardHouse is some base object of type House
method toMatchSnapshot
toMatchSnapshot: { <U extends { [P in keyof T]: any }>( propertyMatchers: Partial<U>, snapshotName?: string ): R; (snapshotName?: string): R;};
This ensures that a value matches the most recent snapshot with property matchers. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information.
method toReturn
toReturn: () => R;
Ensure that a mock function has returned (as opposed to thrown) at least once.
Deprecated
in favor of
toHaveReturned
method toReturnTimes
toReturnTimes: (count: number) => R;
Ensure that a mock function has returned (as opposed to thrown) a specified number of times.
Deprecated
in favor of
toHaveReturnedTimes
method toReturnWith
toReturnWith: <E = any>(value?: E) => R;
Ensure that a mock function has returned a specified value at least once.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
Deprecated
in favor of
toHaveReturnedWith
method toStrictEqual
toStrictEqual: <E = any>(expected: E) => R;
Use to test that objects have the same types as well as structure.
Optionally, you can provide a type for the expected value via a generic. This is particularly useful for ensuring expected objects have the right structure.
method toThrow
toThrow: (error?: string | Constructable | RegExp | Error) => R;
Used to test that a function throws when it is called.
method toThrowError
toThrowError: (error?: string | Constructable | RegExp | Error) => R;
If you want to test that a specific error is thrown inside a function.
Deprecated
in favor of
toThrow
method toThrowErrorMatchingInlineSnapshot
toThrowErrorMatchingInlineSnapshot: (snapshot?: string) => R;
Used to test that a function throws a error matching the most recent snapshot when it is called. Instead of writing the snapshot value to a .snap file, it will be written into the source code automatically.
method toThrowErrorMatchingSnapshot
toThrowErrorMatchingSnapshot: (snapshotName?: string) => R;
Used to test that a function throws a error matching the most recent snapshot when it is called.
interface Mock
interface Mock<T = any, Y extends any[] = any, C = any> extends Function, MockInstance<T, Y, C> {}
construct signature
new (...args: Y): T;
call signature
(this: C, ...args: Y): T;
interface MockContext
interface MockContext<T, Y extends any[], C = any> {}
property calls
calls: Y[];
List of the call arguments of all calls that have been made to the mock.
property contexts
contexts: C[];
List of the call contexts of all calls that have been made to the mock.
property instances
instances: T[];
List of all the object instances that have been instantiated from the mock.
property invocationCallOrder
invocationCallOrder: number[];
List of the call order indexes of the mock. Jest is indexing the order of invocations of all mocks in a test file. The index is starting with
1
.
property lastCall
lastCall?: Y;
List of the call arguments of the last call that was made to the mock. If the function was not called, it will return
undefined
.
property results
results: Array<MockResult<T>>;
List of the results of all calls that have been made to the mock.
interface MockInstance
interface MockInstance<T, Y extends any[], C = any> {}
property mock
mock: MockContext<T, Y, C>;
Provides access to the mock's metadata
method getMockImplementation
getMockImplementation: () => (...args: Y) => T;
Returns the function that was set as the implementation of the mock (using mockImplementation).
method getMockName
getMockName: () => string;
Returns the mock name string set by calling
mockFn.mockName(value)
.
method mockClear
mockClear: () => this;
Resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays.
Often this is useful when you want to clean up a mock's usage data between two assertions.
Beware that
mockClear
will replacemockFn.mock
, not justmockFn.mock.calls
andmockFn.mock.instances
. You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data.
method mockImplementation
mockImplementation: (fn?: (...args: Y) => T) => this;
Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called.
Note:
jest.fn(implementation)
is a shorthand forjest.fn().mockImplementation(implementation)
.
method mockImplementationOnce
mockImplementationOnce: (fn: (...args: Y) => T) => this;
Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results.
Example 1
const myMockFn = jest .fn() .mockImplementationOnce(cb => cb(null, true)) .mockImplementationOnce(cb => cb(null, false));
myMockFn((err, val) => console.log(val)); // true
myMockFn((err, val) => console.log(val)); // false
method mockName
mockName: (name: string) => this;
Sets the name of the mock.
method mockRejectedValue
mockRejectedValue: (value: RejectedValue<T>) => this;
Simple sugar function for:
jest.fn().mockImplementation(() => Promise.reject(value));
Example 1
test('async test', async () => { const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));
await asyncMock(); // throws "Async error" });
method mockRejectedValueOnce
mockRejectedValueOnce: (value: RejectedValue<T>) => this;
Simple sugar function for:
jest.fn().mockImplementationOnce(() => Promise.reject(value));
Example 1
test('async test', async () => { const asyncMock = jest .fn() .mockResolvedValueOnce('first call') .mockRejectedValueOnce(new Error('Async error'));
await asyncMock(); // first call await asyncMock(); // throws "Async error" });
method mockReset
mockReset: () => this;
Resets all information stored in the mock, including any initial implementation and mock name given.
This is useful when you want to completely restore a mock back to its initial state.
Beware that
mockReset
will replacemockFn.mock
, not justmockFn.mock.calls
andmockFn.mock.instances
. You should therefore avoid assigning mockFn.mock to other variables, temporary or not, to make sure you don't access stale data.
method mockResolvedValue
mockResolvedValue: (value: ResolvedValue<T>) => this;
Simple sugar function for:
jest.fn().mockImplementation(() => Promise.resolve(value));
method mockResolvedValueOnce
mockResolvedValueOnce: (value: ResolvedValue<T>) => this;
Simple sugar function for:
jest.fn().mockImplementationOnce(() => Promise.resolve(value));
Example 1
test('async test', async () => { const asyncMock = jest .fn() .mockResolvedValue('default') .mockResolvedValueOnce('first call') .mockResolvedValueOnce('second call');
await asyncMock(); // first call await asyncMock(); // second call await asyncMock(); // default await asyncMock(); // default });
method mockRestore
mockRestore: () => void;
Does everything that
mockFn.mockReset()
does, and also restores the original (non-mocked) implementation.This is useful when you want to mock functions in certain test cases and restore the original implementation in others.
Beware that
mockFn.mockRestore
only works when mock was created withjest.spyOn
. Thus you have to take care of restoration yourself when manually assigningjest.fn()
.The [
restoreMocks
](https://jestjs.io/docs/en/configuration.html#restoremocks-boolean) configuration option is available to restore mocks automatically between tests.
method mockReturnThis
mockReturnThis: () => this;
Just a simple sugar function for:
Example 1
jest.fn(function() { return this; });
method mockReturnValue
mockReturnValue: (value: T) => this;
Accepts a value that will be returned whenever the mock function is called.
Example 1
const mock = jest.fn(); mock.mockReturnValue(42); mock(); // 42 mock.mockReturnValue(43); mock(); // 43
method mockReturnValueOnce
mockReturnValueOnce: (value: T) => this;
Accepts a value that will be returned for one call to the mock function. Can be chained so that successive calls to the mock function return different values. When there are no more
mockReturnValueOnce
values to use, calls will return a value specified bymockReturnValue
.Example 1
const myMockFn = jest.fn() .mockReturnValue('default') .mockReturnValueOnce('first call') .mockReturnValueOnce('second call');
// 'first call', 'second call', 'default', 'default' console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
method withImplementation
withImplementation: { (fn: (...args: Y) => T, callback: () => Promise<unknown>): Promise<void>; (fn: (...args: Y) => T, callback: () => void): void;};
Temporarily overrides the default mock implementation within the callback, then restores its previous implementation.
Remarks
If the callback is async or returns a
thenable
,withImplementation
will return a promise. Awaiting the promise will await the callback and reset the implementation.Temporarily overrides the default mock implementation within the callback, then restores its previous implementation.
interface MockOptions
interface MockOptions {}
property virtual
virtual?: boolean;
interface MockResultIncomplete
interface MockResultIncomplete {}
Represents the result of a single incomplete call to a mock function.
interface MockResultReturn
interface MockResultReturn<T> {}
Represents the result of a single call to a mock function with a return value.
interface MockResultThrow
interface MockResultThrow {}
Represents the result of a single call to a mock function with a thrown error.
interface MockWithArgs
interface MockWithArgs<T extends MockableFunction> extends MockInstance<ReturnType<T>, ArgumentsOf<T>, ConstructorReturnType<T>> {}
construct signature
new (...args: ConstructorArgumentsOf<T>): T;
call signature
(...args: ArgumentsOf<T>): ReturnType<T>;
interface ReplaceProperty
interface ReplaceProperty<K> {}
method replaceValue
replaceValue: (value: K) => this;
Change the value of the property.
method restore
restore: () => void;
Restore property to its original value known at the time of mocking.
interface SpyInstance
interface SpyInstance<T = any, Y extends any[] = any, C = any> extends MockInstance<T, Y, C> {}
type AndNot
type AndNot<T> = T & { not: T;};
type ArgsType
type ArgsType<T> = T extends (...args: infer A) => any ? A : never;
type ArgumentsOf
type ArgumentsOf<T> = T extends (...args: infer A) => any ? A : never;
type Constructor
type Constructor = new (...args: any[]) => any;
type ConstructorArgsType
type ConstructorArgsType<T> = T extends new (...args: infer A) => any ? A : never;
type ConstructorArgumentsOf
type ConstructorArgumentsOf<T> = T extends new (...args: infer A) => any ? A : never;
type ConstructorProperties
type ConstructorProperties<T> = { [K in keyof RemoveIndex<T> as RemoveIndex<T>[K] extends Constructor ? K : never]: RemoveIndex<T>[K];};
type ConstructorPropertyNames
type ConstructorPropertyNames<T> = RemoveIndex<keyof ConstructorProperties<T>>;
type ConstructorReturnType
type ConstructorReturnType<T> = T extends new (...args: any) => infer C ? C : any;
type CustomAsymmetricMatcher
type CustomAsymmetricMatcher<TMatcher extends (...args: any[]) => any> = ( ...args: RemoveFirstFromTuple<Parameters<TMatcher>>) => AsymmetricMatcher;
type CustomAsyncMatchers
type CustomAsyncMatchers<TMatchers extends ExpectExtendMap> = { [K in NonAsyncMatchers<TMatchers>]: CustomAsymmetricMatcher<TMatchers[K]>;};
type CustomJestMatcher
type CustomJestMatcher<TMatcher extends (...args: any[]) => any, TMatcherReturn> = ( ...args: RemoveFirstFromTuple<Parameters<TMatcher>>) => TMatcherReturn;
type CustomMatcher
type CustomMatcher = ( this: MatcherContext, received: any, ...actual: any[]) => CustomMatcherResult | Promise<CustomMatcherResult>;
type EmptyFunction
type EmptyFunction = () => void;
type EqualityTester
type EqualityTester = (a: any, b: any) => boolean | undefined;
type ExpectProperties
type ExpectProperties = { [K in keyof Expect]: Expect[K];};
type ExtendedExpect
type ExtendedExpect<TMatchers extends ExpectExtendMap> = ExpectProperties & AndNot<CustomAsyncMatchers<TMatchers>> & ExtendedExpectFunction<TMatchers>;
type ExtendedExpectFunction
type ExtendedExpectFunction<TMatchers extends ExpectExtendMap> = <TActual>( actual: TActual) => JestExtendedMatchers<TMatchers, TActual>;
type ExtendedMatchers
type ExtendedMatchers< TMatchers extends ExpectExtendMap, TMatcherReturn, TActual> = Matchers<TMatcherReturn, TActual> & { [K in keyof TMatchers]: CustomJestMatcher<TMatchers[K], TMatcherReturn>;};
type Func
type Func = (...args: any[]) => any;
type FunctionProperties
type FunctionProperties<T> = { [K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K];};
type FunctionPropertyNames
type FunctionPropertyNames<T> = keyof FunctionProperties<T>;
type GetAccessor
type GetAccessor = 'get';
type JestExtendedMatchers
type JestExtendedMatchers< TMatchers extends ExpectExtendMap, TActual> = JestMatchersShape< ExtendedMatchers<TMatchers, void, TActual>, ExtendedMatchers<TMatchers, Promise<void>, TActual>>;
type JestMatchers
type JestMatchers<T> = JestMatchersShape< Matchers<void, T>, Matchers<Promise<void>, T>>;
type JestMatchersShape
type JestMatchersShape<TNonPromise extends {} = {}, TPromise extends {} = {}> = { /** * Use resolves to unwrap the value of a fulfilled promise so any other * matcher can be chained. If the promise is rejected the assertion fails. */ resolves: AndNot<TPromise>; /** * Unwraps the reason of a rejected promise so any other matcher can be chained. * If the promise is fulfilled the assertion fails. */ rejects: AndNot<TPromise>;} & AndNot<TNonPromise>;
type Lifecycle
type Lifecycle = (fn: ProvidesHookCallback, timeout?: number) => any;
type MatcherContext
type MatcherContext = MatcherUtils & Readonly<MatcherState>;
type MatcherState
type MatcherState = import('expect').MatcherState;
type MatcherUtils
type MatcherUtils = import('expect').MatcherUtils & { [other: string]: any };
type MaybeMocked
type MaybeMocked<T> = T extends MockableFunction ? MockedFn<T> : T extends object ? MockedObject<T> : T;
type MaybeMockedConstructor
type MaybeMockedConstructor<T> = T extends new (...args: any[]) => infer R ? MockInstance<R, ConstructorArgumentsOf<T>, R> : T;
type MaybeMockedDeep
type MaybeMockedDeep<T> = T extends MockableFunction ? MockedFunctionDeep<T> : T extends object ? MockedObjectDeep<T> : T;
type MethodKeysOf
type MethodKeysOf<T> = { [K in keyof T]: T[K] extends MockableFunction ? K : never;}[keyof T];
type MockableFunction
type MockableFunction = (...args: any[]) => any;
type Mocked
type Mocked<T> = { [P in keyof T]: T[P] extends (this: infer C, ...args: any[]) => any ? MockInstance<ReturnType<T[P]>, ArgsType<T[P]>, C> : T[P] extends Constructable ? MockedClass<T[P]> : T[P];} & T;
Wrap an object or a module with mock definitions
Example 1
jest.mock("../api"); import * as api from "../api";
const mockApi = api as jest.Mocked<typeof api>; api.MyApi.prototype.myApiMethod.mockImplementation(() => "test");
type MockedClass
type MockedClass<T extends Constructable> = MockInstance< InstanceType<T>, T extends new (...args: infer P) => any ? P : never, T extends new (...args: any[]) => infer C ? C : never> & { prototype: T extends { prototype: any } ? Mocked<T['prototype']> : never;} & T;
Wrap a class with mock definitions
Example 1
import { MyClass } from "./library"; jest.mock("./library");
const mockedMyClass = MyClass as jest.MockedClass<typeof MyClass>;
expect(mockedMyClass.mock.calls[0][0]).toBe(42); // Constructor calls expect(mockedMyClass.prototype.myMethod.mock.calls[0][0]).toBe(42); // Method calls
type MockedFn
type MockedFn<T extends MockableFunction> = MockWithArgs<T> & { [K in keyof T]: T[K];};
type MockedFunction
type MockedFunction<T extends (...args: any[]) => any> = MockInstance< ReturnType<T>, ArgsType<T>, T extends (this: infer C, ...args: any[]) => any ? C : never> & T;
Wrap a function with mock definitions
Example 1
import { myFunction } from "./library"; jest.mock("./library");
const mockMyFunction = myFunction as jest.MockedFunction<typeof myFunction>; expect(mockMyFunction.mock.calls[0][0]).toBe(42);
type MockedFunctionDeep
type MockedFunctionDeep<T extends MockableFunction> = MockWithArgs<T> & MockedObjectDeep<T>;
type MockedObject
type MockedObject<T> = MaybeMockedConstructor<T> & { [K in MethodKeysOf<T>]: T[K] extends MockableFunction ? MockedFn<T[K]> : T[K];} & { [K in PropertyKeysOf<T>]: T[K] };
type MockedObjectDeep
type MockedObjectDeep<T> = MaybeMockedConstructor<T> & { [K in MethodKeysOf<T>]: T[K] extends MockableFunction ? MockedFunctionDeep<T[K]> : T[K];} & { [K in PropertyKeysOf<T>]: MaybeMockedDeep<T[K]> };
type MockResult
type MockResult<T> = MockResultReturn<T> | MockResultThrow | MockResultIncomplete;
type NonAsyncMatchers
type NonAsyncMatchers<TMatchers extends ExpectExtendMap> = { [K in keyof TMatchers]: ReturnType< TMatchers[K] > extends Promise<CustomMatcherResult> ? never : K;}[keyof TMatchers];
type NonFunctionPropertyNames
type NonFunctionPropertyNames<T> = keyof { [K in keyof T as T[K] extends Func ? never : K]: T[K];};
type NonPromiseMatchers
type NonPromiseMatchers<T extends JestMatchersShape<any>> = Omit< T, 'resolves' | 'rejects' | 'not'>;
type PromiseMatchers
type PromiseMatchers<T extends JestMatchersShape> = Omit<T['resolves'], 'not'>;
type PropertyAccessors
type PropertyAccessors< M extends keyof T, T extends {}> = M extends NonFunctionPropertyNames<Required<T>> ? GetAccessor | SetAccessor : never;
type PropertyKeysOf
type PropertyKeysOf<T> = { [K in keyof T]: T[K] extends MockableFunction ? never : K;}[keyof T];
type ProvidesCallback
type ProvidesCallback = | ((cb: DoneCallback) => void | undefined) | (() => PromiseLike<unknown>);
type ProvidesHookCallback
type ProvidesHookCallback = (() => any) | ProvidesCallback;
type RejectedValue
type RejectedValue<T> = T extends PromiseLike<any> ? any : never;
type RemoveFirstFromTuple
type RemoveFirstFromTuple<T extends any[]> = T['length'] extends 0 ? [] : ((...b: T) => void) extends (a: any, ...b: infer I) => void ? I : [];
type RemoveIndex
type RemoveIndex<T> = { // from https://stackoverflow.com/a/66252656/4536543 [P in keyof T as string extends P ? never : number extends P ? never : P]: T[P];};
type ResolvedValue
type ResolvedValue<T> = T extends PromiseLike<infer U> ? U | T : never;
type SetAccessor
type SetAccessor = 'set';
type SnapshotSerializerPlugin
type SnapshotSerializerPlugin = import('pretty-format').Plugin;
type Spied
type Spied< T extends (abstract new (...args: any) => any) | ((...args: any) => any)> = T extends abstract new (...args: any) => any ? SpiedClass<T> : T extends (...args: any) => any ? SpiedFunction<T> : never;
Constructs the type of a spied class or function.
type SpiedClass
type SpiedClass<T extends abstract new (...args: any) => any> = SpyInstance< InstanceType<T>, ConstructorParameters<T>, T extends abstract new (...args: any) => infer C ? C : never>;
Constructs the type of a spied class.
type SpiedFunction
type SpiedFunction<T extends (...args: any) => any> = SpyInstance< ReturnType<T>, ArgsType<T>, T extends (this: infer C, ...args: any) => any ? C : never>;
Constructs the type of a spied function.
type SpiedGetter
type SpiedGetter<T> = SpyInstance<T, []>;
Constructs the type of a spied getter.
type SpiedSetter
type SpiedSetter<T> = SpyInstance<void, [T]>;
Constructs the type of a spied setter.
Package Files (1)
Dependencies (2)
Dev Dependencies (0)
No dev dependencies.
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto 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/@types/jest
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@types/jest)
- HTML<a href="https://www.jsdocs.io/package/@types/jest"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5673 ms. - Missing or incorrect documentation? Open an issue for this package.