|
1 | 1 | import { existsSync, readdirSync } from 'node:fs'
|
2 | 2 | import vm from 'node:vm'
|
3 |
| -import { basename, dirname, extname, isAbsolute, join, resolve } from 'pathe' |
| 3 | +import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'pathe' |
4 | 4 | import { getColors, getType } from '@vitest/utils'
|
5 | 5 | import { isNodeBuiltin } from 'vite-node/utils'
|
6 | 6 | import { distDir } from '../paths'
|
@@ -410,8 +410,16 @@ export class VitestMocker {
|
410 | 410 | public mockPath(originalId: string, path: string, external: string | null, factory: MockFactory | undefined, throwIfExists: boolean) {
|
411 | 411 | const id = this.normalizePath(path)
|
412 | 412 |
|
413 |
| - if (throwIfExists && this.moduleCache.has(id)) |
414 |
| - throw new Error(`[vitest] Cannot mock "${originalId}" because it is already loaded. Did you import it in a setup file?\n\nPlease, remove the import if you want static imports to be mocked, or clear module cache by calling "vi.resetModules()" before mocking if you are going to import the file again. See: https://vitest.dev/guide/common-errors.html#cannot-mock-mocked-file.js-because-it-is-already-loaded`) |
| 413 | + const { config } = this.executor.state |
| 414 | + const isIsolatedThreads = config.pool === 'threads' && (config.poolOptions?.threads?.isolate ?? true) |
| 415 | + const isIsolatedForks = config.pool === 'forks' && (config.poolOptions?.forks?.isolate ?? true) |
| 416 | + |
| 417 | + // TODO: find a good way to throw this error even in non-isolated mode |
| 418 | + if (throwIfExists && (isIsolatedThreads || isIsolatedForks)) { |
| 419 | + const cached = this.moduleCache.has(id) && this.moduleCache.getByModuleId(id) |
| 420 | + if (cached && cached.importers.size) |
| 421 | + throw new Error(`[vitest] Cannot mock "${originalId}" because it is already loaded by "${[...cached.importers.values()].map(i => relative(this.root, i)).join('", "')}".\n\nPlease, remove the import if you want static imports to be mocked, or clear module cache by calling "vi.resetModules()" before mocking if you are going to import the file again. See: https://vitest.dev/guide/common-errors.html#cannot-mock-mocked-file-js-because-it-is-already-loaded`) |
| 422 | + } |
415 | 423 |
|
416 | 424 | const suitefile = this.getSuiteFilepath()
|
417 | 425 | const mocks = this.mockMap.get(suitefile) || {}
|
|
0 commit comments