Skip to content

Commit 0d69a73

Browse files
authored
fix(jest-mock): prevent mockImplementationOnce bleeding into withImplementation (#13888)
1 parent d97b760 commit 0d69a73

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
### Fixes
88

99
- `[jest-mock]` Clear mock state when `jest.restoreAllMocks()` is called ([#13867](https://github.com/facebook/jest/pull/13867))
10+
- `[jest-mock]` Prevent `mockImplementationOnce` and `mockReturnValueOnce` bleeding into `withImplementation` ([#13888](https://github.com/facebook/jest/pull/13888))
1011

1112
### Chore & Maintenance
1213

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

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1143,6 +1143,38 @@ describe('moduleMocker', () => {
11431143

11441144
expect.assertions(4);
11451145
});
1146+
1147+
it('mockImplementationOnce does not bleed into withImplementation', () => {
1148+
const mock = jest
1149+
.fn(() => 'outside callback')
1150+
.mockImplementationOnce(() => 'once');
1151+
1152+
mock.withImplementation(
1153+
() => 'inside callback',
1154+
() => {
1155+
expect(mock()).toBe('inside callback');
1156+
},
1157+
);
1158+
1159+
expect(mock()).toBe('once');
1160+
expect(mock()).toBe('outside callback');
1161+
});
1162+
1163+
it('mockReturnValueOnce does not bleed into withImplementation', () => {
1164+
const mock = jest
1165+
.fn(() => 'outside callback')
1166+
.mockReturnValueOnce('once');
1167+
1168+
mock.withImplementation(
1169+
() => 'inside callback',
1170+
() => {
1171+
expect(mock()).toBe('inside callback');
1172+
},
1173+
);
1174+
1175+
expect(mock()).toBe('once');
1176+
expect(mock()).toBe('outside callback');
1177+
});
11461178
});
11471179

11481180
test('mockReturnValue does not override mockImplementationOnce', () => {

packages/jest-mock/src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,16 +840,20 @@ export class ModuleMocker {
840840
// Remember previous mock implementation, then set new one
841841
const mockConfig = this._ensureMockConfig(f);
842842
const previousImplementation = mockConfig.mockImpl;
843+
const previousSpecificImplementations = mockConfig.specificMockImpls;
843844
mockConfig.mockImpl = fn;
845+
mockConfig.specificMockImpls = [];
844846

845847
const returnedValue = callback();
846848

847849
if (isPromise(returnedValue)) {
848850
return returnedValue.then(() => {
849851
mockConfig.mockImpl = previousImplementation;
852+
mockConfig.specificMockImpls = previousSpecificImplementations;
850853
});
851854
} else {
852855
mockConfig.mockImpl = previousImplementation;
856+
mockConfig.specificMockImpls = previousSpecificImplementations;
853857
}
854858
}
855859

0 commit comments

Comments
 (0)