Skip to content
Draft
Changes from all commits
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
40 changes: 28 additions & 12 deletions packages/vitest/src/runtime/moduleRunner/moduleRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,23 +168,39 @@ export class VitestModuleRunner
if (mod.meta && 'mockedModule' in mod.meta) {
const mockedModule = mod.meta.mockedModule as MockedModule
const mockId = this.mocker.getMockPath(mod.id)
// bypass mock and force "importActual" behavior when:
// - mock was removed by doUnmock (stale mockedModule in meta)
// - self-import: mock factory/file is importing the module it's mocking
const isStale = !this.mocker.getDependencyMock(mod.id)
const currentMock = this.mocker.getDependencyMock(mod.id)
if (!currentMock) {
const node = await this.fetchModule(injectQuery(url, '_vitest_original'))
return this._cachedRequest(node.url, node, callstack, metadata)
}
const isSelfImport = callstack.includes(mockId)
|| callstack.includes(url)
|| ('redirect' in mockedModule && callstack.includes(mockedModule.redirect))
if (isStale || isSelfImport) {
|| ('redirect' in currentMock && callstack.includes(currentMock.redirect))
if (isSelfImport) {
const node = await this.fetchModule(injectQuery(url, '_vitest_original'))
return this._cachedRequest(node.url, node, callstack, metadata)
}
mocked = await this.mocker.requestWithMockedModule(
url,
mod,
callstack,
mockedModule,
)
if (currentMock !== mockedModule) {
// Mock was replaced (e.g. manual → automock across test files with
// isolate:false). The module node's meta carries stale code (code: '')
// from the prior manual/redirect mock's fetchModule return. Re-fetch
// the actual module so requestWithMockedModule can evaluate real code.
const freshNode = await this.fetchModule(injectQuery(url, '_vitest_original'))
mocked = await this.mocker.requestWithMockedModule(
url,
freshNode,
callstack,
currentMock,
)
}
else {
mocked = await this.mocker.requestWithMockedModule(
url,
mod,
callstack,
currentMock,
)
}
}
else {
mocked = await this.mocker.mockedRequest(url, mod, callstack)
Expand Down