Skip to content

Commit

Permalink
fix: spyOn should not rely on hasOwnProperty from the spied object
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
cexbrayat committed Aug 3, 2021
1 parent fdc74af commit e1f582a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
12 changes: 12 additions & 0 deletions packages/jest-mock/src/__tests__/index.test.ts
Expand Up @@ -1216,6 +1216,18 @@ describe('moduleMocker', () => {
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).not.toHaveBeenCalled();
});

it('should not rely on hasOwnProperty', () => {
const Foo = Object.assign(Object.create(null), {
foo() {},
});

const spy = moduleMocker.spyOn(Foo, 'foo');

Foo.foo();

expect(spy).toHaveBeenCalled();
});
});

describe('spyOnProperty', () => {
Expand Down
5 changes: 4 additions & 1 deletion packages/jest-mock/src/index.ts
Expand Up @@ -976,7 +976,10 @@ export class ModuleMocker {
);
}

const isMethodOwner = object.hasOwnProperty(methodName);
const isMethodOwner = Object.prototype.hasOwnProperty.call(
object,
methodName,
);

let descriptor = Object.getOwnPropertyDescriptor(object, methodName);
let proto = Object.getPrototypeOf(object);
Expand Down

0 comments on commit e1f582a

Please sign in to comment.