diff --git a/packages/vitest/src/node/execute.ts b/packages/vitest/src/node/execute.ts index 6065c8b4e6bc..95d6daa581ec 100644 --- a/packages/vitest/src/node/execute.ts +++ b/packages/vitest/src/node/execute.ts @@ -83,6 +83,7 @@ export async function executeInViteNode(options: ExecuteOptions) { clearMocks, unmockPath, resolveMockPath, + resolveDependency, } = createMocker(root, mockMap) const result = [] @@ -106,7 +107,7 @@ export async function executeInViteNode(options: ExecuteOptions) { const request = async(dep: string, canMock = true) => { if (canMock) { const mocks = mockMap[suite || ''] || {} - const mock = mocks[dep] + const mock = mocks[resolveDependency(dep)] if (typeof mock === 'function') return callFunctionMock(dep, mock) if (typeof mock === 'string') diff --git a/packages/vitest/src/node/mocker.ts b/packages/vitest/src/node/mocker.ts index 21d170151c92..45a9857ba143 100644 --- a/packages/vitest/src/node/mocker.ts +++ b/packages/vitest/src/node/mocker.ts @@ -1,5 +1,5 @@ import { existsSync, readdirSync } from 'fs' -import { basename, dirname, resolve } from 'pathe' +import { basename, dirname, join, resolve } from 'pathe' import { spies, spyOn } from '../integrations/jest-mock' import { mergeSlashes } from '../utils' @@ -127,6 +127,14 @@ export function createMocker(root: string, mockMap: SuiteMocks) { }) } + // npm resolves as /node_modules, but we store as /@fs/.../node_modules + function resolveDependency(dep: string) { + if (dep.startsWith('/node_modules/')) + return mergeSlashes(`/@fs/${join(root, dep)}`) + + return dep + } + return { mockPath, unmockPath, @@ -136,5 +144,6 @@ export function createMocker(root: string, mockMap: SuiteMocks) { mockObject, getSuiteFilepath, resolveMockPath, + resolveDependency, } }