Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: stop spying on a method, when it's restored #3386

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 11 additions & 6 deletions packages/spy/src/index.ts
Expand Up @@ -213,6 +213,13 @@ function enhanceSpy<TArgs extends any[], TReturns>(
let onceImplementations: ((...args: TArgs) => TReturns)[] = []
let implementationChangedTemporarily = false

function mockCall(this: unknown, ...args: any) {
instances.push(this)
invocations.push(++callOrder)
const impl = implementationChangedTemporarily ? implementation! : (onceImplementations.shift() || implementation || state.getOriginal() || (() => {}))
return impl.apply(this, args)
}

let name: string = (stub as any).name

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

stub.mockRestore = () => {
stub.mockReset()
state.restore()
implementation = undefined
return stub
}

stub.getMockImplementation = () => implementation
stub.mockImplementation = (fn: (...args: TArgs) => TReturns) => {
implementation = fn
state.willCall(mockCall)
return stub
}

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

implementation = fn
state.willCall(mockCall)
implementationChangedTemporarily = true

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

state.willCall(function (this: unknown, ...args) {
instances.push(this)
invocations.push(++callOrder)
const impl = implementationChangedTemporarily ? implementation! : (onceImplementations.shift() || implementation || state.getOriginal() || (() => {}))
return impl.apply(this, args)
})
state.willCall(mockCall)

spies.add(stub)

Expand Down
2 changes: 1 addition & 1 deletion test/core/test/jest-mock.test.ts
Expand Up @@ -261,7 +261,7 @@ describe('jest mock compat layer', () => {
obj.property = true
// unlike jest, mockRestore only restores implementation to the original one,
// we are still spying on the setter
expect(spy).toHaveBeenCalled()
expect(spy).not.toHaveBeenCalled()
expect(obj.property).toBe(true)
})

Expand Down