Skip to content

Commit e1f582a

Browse files
committed
fix: spyOn should not rely on hasOwnProperty from the spied object
The `spyOn` function uses `hasOwnProperty` from the spied object, but this method can be unavailable, for example if the object has the `null` prototype, or if it is a proxy that filters some keys. This arises in Vue 3 projects where the proxies returned by the framework do not expose all methods, and forces the testing library to manually patch the proxies with `hasOwnProperty` to let Jest do its work https://github.com/vuejs/vue-test-utils-next/blob/23d3d3e1f4178a87de5023f5255e0623653affdc/src/mount.ts#L493-L495 This commit changes the code to use `Object.prototype.hasOwnProperty` and fixes this issue.
1 parent fdc74af commit e1f582a

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

packages/jest-mock/src/__tests__/index.test.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1216,6 +1216,18 @@ describe('moduleMocker', () => {
12161216
expect(originalCallArguments[1]).toBe(secondArg);
12171217
expect(spy).not.toHaveBeenCalled();
12181218
});
1219+
1220+
it('should not rely on hasOwnProperty', () => {
1221+
const Foo = Object.assign(Object.create(null), {
1222+
foo() {},
1223+
});
1224+
1225+
const spy = moduleMocker.spyOn(Foo, 'foo');
1226+
1227+
Foo.foo();
1228+
1229+
expect(spy).toHaveBeenCalled();
1230+
});
12191231
});
12201232

12211233
describe('spyOnProperty', () => {

packages/jest-mock/src/index.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -976,7 +976,10 @@ export class ModuleMocker {
976976
);
977977
}
978978

979-
const isMethodOwner = object.hasOwnProperty(methodName);
979+
const isMethodOwner = Object.prototype.hasOwnProperty.call(
980+
object,
981+
methodName,
982+
);
980983

981984
let descriptor = Object.getOwnPropertyDescriptor(object, methodName);
982985
let proto = Object.getPrototypeOf(object);

0 commit comments

Comments
 (0)