Skip to content

Commit 5c68cff

Browse files
committed
fix(jest-mock): fix mock restoration reassigning to previously unexisting prop (#8625)
1 parent a501718 commit 5c68cff

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
- `[jest-haste-map]` Don't throw on missing mapper in Node crawler ([#8558](https://github.com/facebook/jest/pull/8558))
2323
- `[jest-core]` Fix incorrect `passWithNoTests` warning ([#8595](https://github.com/facebook/jest/pull/8595))
2424
- `[jest-snapshots]` Fix test retries that contain snapshots ([#8629](https://github.com/facebook/jest/pull/8629))
25+
- `[jest-mock]` Fix incorrect assignments when restoring mocks in instances where they originally didn't exist ([#8631](https://github.com/facebook/jest/pull/8631))
2526

2627
### Chore & Maintenance
2728

packages/jest-mock/src/__tests__/index.test.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,32 @@ describe('moduleMocker', () => {
542542
});
543543
});
544544

545+
it('mocks the method in the passed object itself', () => {
546+
const parent = {func: () => 'abcd'};
547+
const child = Object.create(parent);
548+
549+
moduleMocker.spyOn(child, 'func').mockReturnValue('efgh');
550+
551+
expect(child.hasOwnProperty('func')).toBe(true);
552+
expect(child.func()).toEqual('efgh');
553+
expect(parent.func()).toEqual('abcd');
554+
});
555+
556+
it('should delete previously inexistent methods when restoring', () => {
557+
const parent = {func: () => 'abcd'};
558+
const child = Object.create(parent);
559+
560+
moduleMocker.spyOn(child, 'func').mockReturnValue('efgh');
561+
562+
moduleMocker.restoreAllMocks();
563+
expect(child.func()).toEqual('abcd');
564+
565+
moduleMocker.spyOn(parent, 'func').mockReturnValue('jklm');
566+
567+
expect(child.hasOwnProperty('func')).toBe(false);
568+
expect(child.func()).toEqual('jklm');
569+
});
570+
545571
it('supports mock value returning undefined', () => {
546572
const obj = {
547573
func: () => 'some text',

packages/jest-mock/src/index.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1009,9 +1009,15 @@ class ModuleMockerClass {
10091009
);
10101010
}
10111011

1012+
const isMethodOwner = object.hasOwnProperty(methodName);
1013+
10121014
// @ts-ignore overriding original method with a Mock
10131015
object[methodName] = this._makeComponent({type: 'function'}, () => {
1014-
object[methodName] = original;
1016+
if (isMethodOwner) {
1017+
object[methodName] = original;
1018+
} else {
1019+
delete object[methodName];
1020+
}
10151021
});
10161022

10171023
// @ts-ignore original method is now a Mock

0 commit comments

Comments
 (0)