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 11, 2019
1 parent a501718 commit 1ad9864
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -22,6 +22,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
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
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 1ad9864

Please sign in to comment.