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(spy)!: reset existing spy on repeated spyOn #7359

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/spy/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ export function spyOn<T, K extends keyof T>(

const currentStub = getSpy(obj, method, accessType)
if (currentStub) {
return currentStub
currentStub.mockRestore()
}

const stub = tinyspy.internalSpyOn(obj, objMethod as any)
Expand Down
42 changes: 38 additions & 4 deletions test/core/test/jest-mock.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -363,29 +363,63 @@ describe('jest mock compat layer', () => {
expect(obj.property).toBe(true)
})

it('spyOn returns the same spy twice', () => {
it('spyOn multiple times', () => {
const obj = {
method() {
return 'original'
},
}

const spy1 = vi.spyOn(obj, 'method').mockImplementation(() => 'mocked')
const spy2 = vi.spyOn(obj, 'method')

expect(vi.isMockFunction(obj.method)).toBe(true)
expect(obj.method()).toBe('mocked')
expect(spy1).toBe(spy2)
expect(spy1.mock.results).toMatchInlineSnapshot(`
[
{
"type": "return",
"value": "mocked",
},
]
`)

const spy2 = vi.spyOn(obj, 'method') // this calls `spy1.mockRestore()`
expect(vi.isMockFunction(obj.method)).toBe(true)
expect(obj.method()).toBe('original')
expect(spy1).not.toBe(spy2)
expect(spy1.mock.results).toMatchInlineSnapshot(`[]`)
expect(spy2.mock.results).toMatchInlineSnapshot(`
[
{
"type": "return",
"value": "original",
},
]
`)

spy2.mockImplementation(() => 'mocked2')

expect(obj.method()).toBe('mocked2')
expect(spy1.mock.results).toMatchInlineSnapshot(`[]`)
expect(spy2.mock.results).toMatchInlineSnapshot(`
[
{
"type": "return",
"value": "original",
},
{
"type": "return",
"value": "mocked2",
},
]
`)

spy2.mockRestore()

expect(obj.method()).toBe('original')
expect(vi.isMockFunction(obj.method)).toBe(false)
expect(obj.method).not.toBe(spy1)
expect(spy1.mock.results).toMatchInlineSnapshot(`[]`)
expect(spy2.mock.results).toMatchInlineSnapshot(`[]`)
})

it('should spy on property setter (2), and mockReset should not restore original descriptor', () => {
Expand Down
Loading