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: don't hang on mocking module with circular dependency #2572

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
5 changes: 5 additions & 0 deletions examples/mocks/src/export-default-circle-b.ts
@@ -0,0 +1,5 @@
import b from './export-default-circle-index'

export default function () {
return b()
}
5 changes: 5 additions & 0 deletions examples/mocks/src/export-default-circle-index.ts
@@ -0,0 +1,5 @@
import b from './export-default-circle-b'

export default function () {
return b()
}
9 changes: 8 additions & 1 deletion examples/mocks/test/circular.spec.ts
@@ -1,11 +1,18 @@
import { expect, test, vi } from 'vitest'
import { main } from '../src/main.js'
import x from '../src/export-default-circle-index'

vi.mock('../src/A', async () => ({
...(await vi.importActual<any>('../src/A')),
funcA: () => 'mockedA',
}))

test('main', () => {
vi.mock('../src/export-default-circle-b')

test('can import actual inside mock factory', () => {
expect(main()).toBe('mockedA')
})

test('can mock a circular dependency', () => {
expect(x()).toBe(undefined)
})
4 changes: 2 additions & 2 deletions packages/vitest/src/runtime/mocker.ts
Expand Up @@ -359,13 +359,13 @@ export class VitestMocker {

if (mock === null) {
const cache = this.moduleCache.get(mockPath)
if (cache?.exports)
if (cache.exports)
return cache.exports

const exports = {}
// Assign the empty exports object early to allow for cycles to work. The object will be filled by mockObject()
this.moduleCache.set(mockPath, { exports })
const mod = await this.runner.directRequest(url, url, [])
const mod = await this.runner.directRequest(url, url, callstack)
this.mockObject(mod, exports)
return exports
}
Expand Down