;
isMockFunction, R>(
fn: (...args: P) => R,
): fn is Mock<(...args: P) => R>;
isMockFunction(fn: unknown): fn is Mock;
isMockFunction(fn: unknown): fn is Mock {
return fn != null && (fn as Mock)._isMockFunction === true;
}
fn(implementation?: T): Mock {
const length = implementation ? implementation.length : 0;
const fn = this._makeComponent({
length,
type: 'function',
});
if (implementation) {
fn.mockImplementation(implementation);
}
return fn;
}
spyOn<
T extends object,
K extends PropertyLikeKeys,
V extends Required[K],
A extends 'get' | 'set',
>(
object: T,
methodKey: K,
accessType: A,
): A extends 'get'
? SpiedGetter
: A extends 'set'
? SpiedSetter
: never;
spyOn<
T extends object,
K extends ConstructorLikeKeys | MethodLikeKeys,
V extends Required[K],
>(
object: T,
methodKey: K,
): V extends ClassLike | FunctionLike ? Spied : never;
spyOn(
object: T,
methodKey: keyof T,
accessType?: 'get' | 'set',
): MockInstance {
if (
object == null ||
(typeof object !== 'object' && typeof object !== 'function')
) {
throw new Error(
`Cannot use spyOn on a primitive value; ${this._typeOf(object)} given`,
);
}
if (methodKey == null) {
throw new Error('No property name supplied');
}
if (accessType) {
return this._spyOnProperty(object, methodKey, accessType);
}
const original = object[methodKey];
if (!original) {
throw new Error(
`Property \`${String(
methodKey,
)}\` does not exist in the provided object`,
);
}
if (!this.isMockFunction(original)) {
if (typeof original !== 'function') {
throw new TypeError(
`Cannot spy on the \`${String(
methodKey,
)}\` property because it is not a function; ${this._typeOf(
original,
)} given instead.${
typeof original === 'object'
? ''
: ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String(
methodKey,
)}', value)\` instead.`
}`,
);
}
const isMethodOwner = Object.prototype.hasOwnProperty.call(
object,
methodKey,
);
let descriptor = Object.getOwnPropertyDescriptor(object, methodKey);
let proto = Object.getPrototypeOf(object);
while (!descriptor && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, methodKey);
proto = Object.getPrototypeOf(proto);
}
let mock: Mock;
if (descriptor && descriptor.get) {
const originalGet = descriptor.get;
mock = this._makeComponent({type: 'function'}, () => {
if (isMethodOwner) {
descriptor!.get = originalGet;
Object.defineProperty(object, methodKey, descriptor!);
} else {
delete object[methodKey];
}
});
descriptor.get = () => mock;
Object.defineProperty(object, methodKey, descriptor);
} else {
mock = this._makeComponent({type: 'function'}, () => {
if (isMethodOwner) {
object[methodKey] = original;
} else {
delete object[methodKey];
}
});
// @ts-expect-error overriding original method with a Mock
object[methodKey] = mock;
}
mock.mockImplementation(function (this: unknown) {
return original.apply(this, arguments);
});
}
return object[methodKey] as Mock;
}
private _spyOnProperty(
object: T,
propertyKey: keyof T,
accessType: 'get' | 'set',
): MockInstance {
const isPropertyOwner = Object.prototype.hasOwnProperty.call(
object,
propertyKey,
);
let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey);
let proto = Object.getPrototypeOf(object);
while (!descriptor && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey);
proto = Object.getPrototypeOf(proto);
}
if (!descriptor) {
throw new Error(
`Property \`${String(
propertyKey,
)}\` does not exist in the provided object`,
);
}
if (!descriptor.configurable) {
throw new Error(
`Property \`${String(propertyKey)}\` is not declared configurable`,
);
}
if (!descriptor[accessType]) {
throw new Error(
`Property \`${String(
propertyKey,
)}\` does not have access type ${accessType}`,
);
}
const original = descriptor[accessType];
if (!this.isMockFunction(original)) {
if (typeof original !== 'function') {
throw new TypeError(
`Cannot spy on the ${String(
propertyKey,
)} property because it is not a function; ${this._typeOf(
original,
)} given instead.${
typeof original === 'object'
? ''
: ` If you are trying to mock a property, use \`jest.replaceProperty(object, '${String(
propertyKey,
)}', value)\` instead.`
}`,
);
}
descriptor[accessType] = this._makeComponent({type: 'function'}, () => {
if (isPropertyOwner) {
// @ts-expect-error: mock is assignable
descriptor![accessType] = original;
Object.defineProperty(object, propertyKey, descriptor!);
} else {
// Inherited accessor: drop the own property the spy installed so the
// prototype accessor is exposed again instead of a stale copy.
delete object[propertyKey];
}
});
(descriptor[accessType] as Mock).mockImplementation(function (
this: unknown,
) {
// @ts-expect-error - wrong context
return original.apply(this, arguments);
});
}
Object.defineProperty(object, propertyKey, descriptor);
return descriptor[accessType] as Mock;
}
replaceProperty(
object: T,
propertyKey: K,
value: T[K],
): Replaced {
if (
object == null ||
(typeof object !== 'object' && typeof object !== 'function')
) {
throw new Error(
`Cannot use replaceProperty on a primitive value; ${this._typeOf(
object,
)} given`,
);
}
if (propertyKey == null) {
throw new Error('No property name supplied');
}
let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey);
let proto = Object.getPrototypeOf(object);
while (!descriptor && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey);
proto = Object.getPrototypeOf(proto);
}
if (!descriptor) {
throw new Error(
`Property \`${String(
propertyKey,
)}\` does not exist in the provided object`,
);
}
if (!descriptor.configurable) {
throw new Error(
`Property \`${String(propertyKey)}\` is not declared configurable`,
);
}
if (descriptor.get !== undefined) {
throw new Error(
`Cannot replace the \`${String(
propertyKey,
)}\` property because it has a getter. Use \`jest.spyOn(object, '${String(
propertyKey,
)}', 'get').mockReturnValue(value)\` instead.`,
);
}
if (descriptor.set !== undefined) {
throw new Error(
`Cannot replace the \`${String(
propertyKey,
)}\` property because it has a setter. Use \`jest.spyOn(object, '${String(
propertyKey,
)}', 'set').mockReturnValue(value)\` instead.`,
);
}
if (typeof descriptor.value === 'function') {
throw new TypeError(
`Cannot replace the \`${String(
propertyKey,
)}\` property because it is a function. Use \`jest.spyOn(object, '${String(
propertyKey,
)}')\` instead.`,
);
}
const existingRestore = this._findReplacedProperty(object, propertyKey);
if (existingRestore) {
return existingRestore.replaced.replaceValue(value);
}
const isPropertyOwner = Object.prototype.hasOwnProperty.call(
object,
propertyKey,
);
const originalValue = descriptor.value;
const restore: ReplacedPropertyRestorer = () => {
if (isPropertyOwner) {
object[propertyKey] = originalValue;
} else {
delete object[propertyKey];
}
};
const replaced: Replaced = {
replaceValue: value => {
object[propertyKey] = value;
return replaced;
},
restore: () => {
restore();
this._spyState.delete(restore);
},
};
restore.object = object;
restore.property = propertyKey;
restore.replaced = replaced;
this._spyState.add(restore);
return replaced.replaceValue(value);
}
clearAllMocks(): void {
this._mockState = new WeakMap();
}
/**
* Walks the own keys of `scope` and calls `.mockClear()` on each value that
* is a Jest mock function. Used by `resetModules` to clear mocks that user
* code installed directly on the test environment's global object (where
* the mock-fn registry doesn't see them).
*/
clearMocksOnScope(scope: object): void {
for (const key of Object.keys(scope)) {
const value = (scope as Record)[key];
// Gate on `'_isMockFunction' in value` first: that uses the `has` trap
// and won't fire a throwing getter (e.g. a user Proxy on `globalThis`).
// `isMockFunction` reads `._isMockFunction` directly, so we only call
// it once we know the property exists. The extra `typeof mockClear`
// guard rejects forged values that set the marker but aren't real Jest
// mocks.
if (
value != null &&
(typeof value === 'object' || typeof value === 'function') &&
'_isMockFunction' in value &&
this.isMockFunction(value) &&
typeof (value as Mock).mockClear === 'function'
) {
(value as Mock).mockClear();
}
}
}
resetAllMocks(): void {
this._mockConfigRegistry = new WeakMap();
this._mockState = new WeakMap();
}
restoreAllMocks(): void {
for (const restore of this._spyState) restore();
this._spyState = new Set();
}
private _typeOf(value: unknown): string {
return value == null ? `${value}` : typeof value;
}
mocked(source: T, options?: {shallow: false}): Mocked;
mocked(
source: T,
options: {shallow: true},
): MockedShallow;
mocked(
source: T,
_options?: {shallow: boolean},
): Mocked | MockedShallow {
return source as Mocked | MockedShallow;
}
}
const JestMock = new ModuleMocker(globalThis);
export const fn = JestMock.fn.bind(JestMock);
export const spyOn = JestMock.spyOn.bind(JestMock);
export const mocked = JestMock.mocked.bind(JestMock);
export const replaceProperty = JestMock.replaceProperty.bind(JestMock);