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: clear mock from callstack, if mocked with factory #1276

Merged
merged 2 commits into from May 9, 2022
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
@@ -1,13 +1,8 @@
import actualCreate from 'zustand'

// a variable to hold reset functions for all stores declared in the app
const storeResetFns = new Set()

// when creating a store, we get its initial state, create a reset function and add it in the set
const create = vi.fn((createState) => {
const store = actualCreate(createState)
const initialState = store.getState()
storeResetFns.add(() => store.setState(initialState, true))
return store
})

Expand Down
5 changes: 5 additions & 0 deletions examples/mocks/src/zustand-magic.ts
@@ -0,0 +1,5 @@
import zustand from 'zustand'

export const magic = () => {
return zustand()
}
7 changes: 7 additions & 0 deletions examples/mocks/test/self-importing.test.ts
@@ -1,9 +1,16 @@
import zustand from 'zustand'
import { magic } from '../src/zustand-magic'

vi.mock('zustand')

describe('zustand didn\'t go into an infinite loop', () => {
test('zustand is mocked', () => {
expect(vi.isMockFunction(zustand)).toBe(true)
})

test('magic calls zustand', () => {
const store = magic()
expect(zustand).toHaveBeenCalled()
expect(store).toBeTypeOf('function')
})
})
5 changes: 4 additions & 1 deletion packages/vitest/src/runtime/mocker.ts
Expand Up @@ -250,7 +250,10 @@ export class VitestMocker {
}
if (typeof mock === 'function' && !callstack.includes(`mock:${dep}`)) {
callstack.push(`mock:${dep}`)
return this.callFunctionMock(dep, mock)
const result = await this.callFunctionMock(dep, mock)
const indexMock = callstack.indexOf(`mock:${dep}`)
callstack.splice(indexMock, 1)
return result
}
if (typeof mock === 'string' && !callstack.includes(mock))
dep = mock
Expand Down