Skip to content

Commit 2cb1a15

Browse files
authoredMay 17, 2023
fix: stop spying on a method, when it's restored (#3386)
1 parent dcf1346 commit 2cb1a15

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed
 

‎packages/spy/src/index.ts

+11-6
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,13 @@ function enhanceSpy<TArgs extends any[], TReturns>(
213213
let onceImplementations: ((...args: TArgs) => TReturns)[] = []
214214
let implementationChangedTemporarily = false
215215

216+
function mockCall(this: unknown, ...args: any) {
217+
instances.push(this)
218+
invocations.push(++callOrder)
219+
const impl = implementationChangedTemporarily ? implementation! : (onceImplementations.shift() || implementation || state.getOriginal() || (() => {}))
220+
return impl.apply(this, args)
221+
}
222+
216223
let name: string = (stub as any).name
217224

218225
stub.getMockName = () => name || 'vi.fn()'
@@ -237,13 +244,15 @@ function enhanceSpy<TArgs extends any[], TReturns>(
237244

238245
stub.mockRestore = () => {
239246
stub.mockReset()
247+
state.restore()
240248
implementation = undefined
241249
return stub
242250
}
243251

244252
stub.getMockImplementation = () => implementation
245253
stub.mockImplementation = (fn: (...args: TArgs) => TReturns) => {
246254
implementation = fn
255+
state.willCall(mockCall)
247256
return stub
248257
}
249258

@@ -258,6 +267,7 @@ function enhanceSpy<TArgs extends any[], TReturns>(
258267
const originalImplementation = implementation
259268

260269
implementation = fn
270+
state.willCall(mockCall)
261271
implementationChangedTemporarily = true
262272

263273
const reset = () => {
@@ -305,12 +315,7 @@ function enhanceSpy<TArgs extends any[], TReturns>(
305315
get: () => mockContext,
306316
})
307317

308-
state.willCall(function (this: unknown, ...args) {
309-
instances.push(this)
310-
invocations.push(++callOrder)
311-
const impl = implementationChangedTemporarily ? implementation! : (onceImplementations.shift() || implementation || state.getOriginal() || (() => {}))
312-
return impl.apply(this, args)
313-
})
318+
state.willCall(mockCall)
314319

315320
spies.add(stub)
316321

‎test/core/test/jest-mock.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ describe('jest mock compat layer', () => {
261261
obj.property = true
262262
// unlike jest, mockRestore only restores implementation to the original one,
263263
// we are still spying on the setter
264-
expect(spy).toHaveBeenCalled()
264+
expect(spy).not.toHaveBeenCalled()
265265
expect(obj.property).toBe(true)
266266
})
267267

0 commit comments

Comments
 (0)
Please sign in to comment.