Skip to content

Commit

Permalink
fix: don't hang when mocking module with circular dependency (#2572)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Dec 28, 2022
1 parent 9f41edd commit c479d9c
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 3 deletions.
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

0 comments on commit c479d9c

Please sign in to comment.