Skip to content

Commit

Permalink
refactor(jest-mock): clean up internal typings more (#13575)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrazauskas committed Nov 8, 2022
1 parent a570638 commit ba20c15
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions packages/jest-mock/src/index.ts
Expand Up @@ -1089,12 +1089,11 @@ export class ModuleMocker {
methodKey: K,
): V extends ClassLike | FunctionLike ? Spied<V> : never;

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
spyOn<T extends object, K extends PropertyLikeKeys<T>>(
spyOn<T extends object>(
object: T,
methodKey: K,
methodKey: keyof T,
accessType?: 'get' | 'set',
) {
): MockInstance {
if (typeof object !== 'object' && typeof object !== 'function') {
throw new Error(
`Cannot spyOn on a primitive value; ${this._typeOf(object)} given`,
Expand Down Expand Up @@ -1168,16 +1167,16 @@ export class ModuleMocker {
});
}

return object[methodKey];
return object[methodKey] as Mock;
}

private _spyOnProperty<T extends object, K extends PropertyLikeKeys<T>>(
obj: T,
propertyKey: K,
private _spyOnProperty<T extends object>(
object: T,
propertyKey: keyof T,
accessType: 'get' | 'set',
): Mock<() => T> {
let descriptor = Object.getOwnPropertyDescriptor(obj, propertyKey);
let proto = Object.getPrototypeOf(obj);
): MockInstance {
let descriptor = Object.getOwnPropertyDescriptor(object, propertyKey);
let proto = Object.getPrototypeOf(object);

while (!descriptor && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, propertyKey);
Expand Down Expand Up @@ -1216,19 +1215,19 @@ export class ModuleMocker {
descriptor[accessType] = this._makeComponent({type: 'function'}, () => {
// @ts-expect-error: mock is assignable
descriptor![accessType] = original;
Object.defineProperty(obj, propertyKey, descriptor!);
Object.defineProperty(object, propertyKey, descriptor!);
});

(descriptor[accessType] as Mock<() => T>).mockImplementation(function (
(descriptor[accessType] as Mock).mockImplementation(function (
this: unknown,
) {
// @ts-expect-error - wrong context
return original.apply(this, arguments);
});
}

Object.defineProperty(obj, propertyKey, descriptor);
return descriptor[accessType] as Mock<() => T>;
Object.defineProperty(object, propertyKey, descriptor);
return descriptor[accessType] as Mock;
}

clearAllMocks(): void {
Expand Down

0 comments on commit ba20c15

Please sign in to comment.