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 4, 2021
1 parent fdc74af commit d614bb1
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@

- `[docs]` Correct expects.assertions documentation by adding async/await for asynchronous function.

### Fixes

- `[jest-mock]` Fix `spyOn` to use `Object.prototype.hasOwnProperty` [#11721](https://github.com/facebook/jest/pull/11721)

## 27.0.6

### Fixes
Expand Down
12 changes: 12 additions & 0 deletions packages/jest-mock/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1216,6 +1216,18 @@ describe('moduleMocker', () => {
expect(originalCallArguments[1]).toBe(secondArg);
expect(spy).not.toHaveBeenCalled();
});

it('should work with object of null prototype', () => {
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
Original file line number Diff line number Diff line change
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 d614bb1

Please sign in to comment.