Skip to content

Commit

Permalink
fix: resolve node_module mock in npm (#284)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed Dec 28, 2021
1 parent e474317 commit 20e1749
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
3 changes: 2 additions & 1 deletion packages/vitest/src/node/execute.ts
Expand Up @@ -83,6 +83,7 @@ export async function executeInViteNode(options: ExecuteOptions) {
clearMocks,
unmockPath,
resolveMockPath,
resolveDependency,
} = createMocker(root, mockMap)

const result = []
Expand All @@ -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')
Expand Down
11 changes: 10 additions & 1 deletion 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'

Expand Down Expand Up @@ -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,
Expand All @@ -136,5 +144,6 @@ export function createMocker(root: string, mockMap: SuiteMocks) {
mockObject,
getSuiteFilepath,
resolveMockPath,
resolveDependency,
}
}

1 comment on commit 20e1749

@11joselu
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In love with you fix @sheremet-va. I never thought it was so easy.

Great job!!!

Please sign in to comment.