Skip to content

Commit

Permalink
fix(jest-mock): fix mock restoration reassigning to previously unexis…
Browse files Browse the repository at this point in the history
…ting prop (#8625)
  • Loading branch information
lucasfcosta committed Jul 2, 2019
1 parent 10f7345 commit 1a08a06
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- `[jest-snapshot]` Prevent inline snapshots from drifting when inline snapshots are updated ([#8492](https://github.com/facebook/jest/pull/8492))
- `[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-mock]` Fix incorrect assignments when restoring mocks in instances where they originally didn't exist ([#8625](https://github.com/facebook/jest/pull/8625))

### Chore & Maintenance

Expand Down
23 changes: 23 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,29 @@ 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();
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 1a08a06

Please sign in to comment.