diff --git a/packages/vitest/src/runtime/moduleRunner/moduleRunner.ts b/packages/vitest/src/runtime/moduleRunner/moduleRunner.ts index be655b57f8af..197023e09bba 100644 --- a/packages/vitest/src/runtime/moduleRunner/moduleRunner.ts +++ b/packages/vitest/src/runtime/moduleRunner/moduleRunner.ts @@ -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)