Skip to content

Commit

Permalink
Fix mock reassigning to previously inexistent method (#8631)
Browse files Browse the repository at this point in the history
  • Loading branch information
lucasfcosta authored and jeysal committed Jul 11, 2019
1 parent 517235a commit b76f01b
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
- `[jest-haste-map]` Don't throw on missing mapper in Node crawler ([#8558](https://github.com/facebook/jest/pull/8558))
- `[jest-core]` Fix incorrect `passWithNoTests` warning ([#8595](https://github.com/facebook/jest/pull/8595))
- `[jest-snapshots]` Fix test retries that contain snapshots ([#8629](https://github.com/facebook/jest/pull/8629))
- `[jest-mock]` Fix incorrect assignments when restoring mocks in instances where they originally didn't exist ([#8631](https://github.com/facebook/jest/pull/8631))

### Chore & Maintenance

Expand Down
26 changes: 26 additions & 0 deletions packages/jest-mock/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,32 @@ describe('moduleMocker', () => {
});
});

it('mocks the method in the passed object itself', () => {
const parent = {func: () => 'abcd'};
const child = Object.create(parent);

moduleMocker.spyOn(child, 'func').mockReturnValue('efgh');

expect(child.hasOwnProperty('func')).toBe(true);
expect(child.func()).toEqual('efgh');
expect(parent.func()).toEqual('abcd');
});

it('should delete previously inexistent methods when restoring', () => {
const parent = {func: () => 'abcd'};
const child = Object.create(parent);

moduleMocker.spyOn(child, 'func').mockReturnValue('efgh');

moduleMocker.restoreAllMocks();
expect(child.func()).toEqual('abcd');

moduleMocker.spyOn(parent, 'func').mockReturnValue('jklm');

expect(child.hasOwnProperty('func')).toBe(false);
expect(child.func()).toEqual('jklm');
});

it('supports mock value returning undefined', () => {
const obj = {
func: () => 'some text',
Expand Down
8 changes: 7 additions & 1 deletion packages/jest-mock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1009,9 +1009,15 @@ class ModuleMockerClass {
);
}

const isMethodOwner = object.hasOwnProperty(methodName);

// @ts-ignore overriding original method with a Mock
object[methodName] = this._makeComponent({type: 'function'}, () => {
object[methodName] = original;
if (isMethodOwner) {
object[methodName] = original;
} else {
delete object[methodName];
}
});

// @ts-ignore original method is now a Mock
Expand Down

0 comments on commit b76f01b

Please sign in to comment.