Skip to content

Commit 2c9559c

Browse files
hi-ogawaBrooooooklynclaudesheremet-va
authored
fix(mocker): hoist vi.mock() for vite-plus/test imports [backport to v4] (#10548)
Co-authored-by: LongYinan <lynweklm@gmail.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Vladimir <sleuths.slews0s@icloud.com>
1 parent 3080388 commit 2c9559c

2 files changed

Lines changed: 24 additions & 2 deletions

File tree

packages/mocker/src/node/hoistMocks.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,12 @@ const regexpHoistable
7474
= /\b(?:vi|vitest)\s*\.\s*(?:mock|unmock|hoisted|doMock|doUnmock)\s*\(/
7575
const hashbangRE = /^#!.*\n/
7676

77+
// Public redistributions of Vitest that re-export its mocking API (`vi`)
78+
// verbatim under their own specifier. Imports from these are treated as the
79+
// hoisted module so `vi.mock()` is hoisted for e.g.
80+
// `import { vi } from 'vite-plus/test'`, exactly as it is for `vitest`.
81+
const REDISTRIBUTED_HOISTED_MODULES = ['vite-plus/test']
82+
7783
// this is a fork of Vite SSR transform
7884
export function hoistMocks(
7985
code: string,
@@ -132,8 +138,9 @@ export function hoistMocks(
132138
) {
133139
const source = importNode.source.value as string
134140
// always hoist vitest import to top of the file, so
135-
// "vi" helpers can access it
136-
if (hoistedModule === source) {
141+
// "vi" helpers can access it. Vitest redistributions that re-export the
142+
// mocking API under their own specifier are recognized the same way.
143+
if (hoistedModule === source || REDISTRIBUTED_HOISTED_MODULES.includes(source)) {
137144
hoistedModuleImported = true
138145
return
139146
}

test/core/test/injector-mock.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,21 @@ import { test } from 'vitest'
5757
`)
5858
})
5959

60+
test('recognizes the vite-plus/test redistribution as the hoisted module', () => {
61+
expect(hoistSimpleCode(`
62+
import { vi } from 'vite-plus/test'
63+
vi.mock('path', () => {})
64+
vi.unmock('path')
65+
vi.hoisted(() => {})
66+
`)).toMatchInlineSnapshot(`
67+
"vi.mock('path', () => {})
68+
vi.unmock('path')
69+
vi.hoisted(() => {})
70+
71+
import { vi } from 'vite-plus/test'"
72+
`)
73+
})
74+
6075
test('always hoists all imports but they are under mocks', () => {
6176
expect(hoistSimpleCode(`
6277
import { vi } from 'vitest'

0 commit comments

Comments
 (0)