Skip to content

Commit 06208d3

Browse files
authored
fix(mocker): support mocking builtins without node: prefix (#8829)
1 parent 807d1ff commit 06208d3

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

packages/vitest/src/node/pools/rpc.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import type { RuntimeRPC } from '../../types/rpc'
22
import type { TestProject } from '../project'
33
import type { ResolveSnapshotPathHandlerContext } from '../types/config'
44
import { existsSync, mkdirSync } from 'node:fs'
5+
import { isBuiltin } from 'node:module'
56
import { fileURLToPath } from 'node:url'
67
import { cleanUrl } from '@vitest/utils/helpers'
78
import { handleRollupError } from '../environments/fetchModule'
@@ -63,6 +64,17 @@ export function createMethodsRPC(project: TestProject, options: MethodsOptions =
6364
if (!resolved) {
6465
return null
6566
}
67+
const file = cleanUrl(resolved.id)
68+
if (resolved.external) {
69+
return {
70+
file,
71+
// TODO: use isBuiltin defined in the environment
72+
url: !resolved.id.startsWith('node:') && isBuiltin(resolved.id)
73+
? `node:${resolved.id}`
74+
: resolved.id,
75+
id: resolved.id,
76+
}
77+
}
6678
return {
6779
file: cleanUrl(resolved.id),
6880
url: normalizeResolvedIdToUrl(environment, resolved.id),
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
/* eslint-disable unicorn/prefer-node-protocol */
2+
3+
import fs from 'fs/promises'
4+
import { expect, test, vi } from 'vitest'
5+
6+
vi.mock(import('fs/promises'), async (importOriginal) => {
7+
const { default: original } = await importOriginal()
8+
return {
9+
default: {
10+
...original,
11+
readFile: vi.fn(),
12+
},
13+
}
14+
})
15+
16+
test('fs is defined when node: prefix is not used', () => {
17+
expect(vi.isMockFunction(fs.readFile)).toBe(true)
18+
})

0 commit comments

Comments
 (0)