Skip to content

Commit ff93a57

Browse files
authored
fix(vitest): correctly hoist vi.hoisted if assigned (#4285)
1 parent eac7776 commit ff93a57

File tree

4 files changed

+42
-1
lines changed

4 files changed

+42
-1
lines changed

packages/vitest/src/node/hoistMocks.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,11 @@ function transformImportSpecifiers(node: ImportDeclaration) {
4646
}
4747

4848
const regexpHoistable = /^[ \t]*\b(vi|vitest)\s*\.\s*(mock|unmock|hoisted)\(/m
49+
const regexpAssignedHoisted = /=[ \t]*(\bawait|)[ \t]*\b(vi|vitest)\s*\.\s*hoisted\(/
4950
const hashbangRE = /^#!.*\n/
5051

5152
export function hoistMocks(code: string, id: string, parse: (code: string, options: any) => AcornNode) {
52-
const hasMocks = regexpHoistable.test(code)
53+
const hasMocks = regexpHoistable.test(code) || regexpAssignedHoisted.test(code)
5354

5455
if (!hasMocks)
5556
return

test/core/src/rely-on-hoisted.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// @ts-expect-error not typed global
2+
export const value = globalThis.someGlobalValue
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// this test checks only vi.hoisted because vi.mock affects the regexp to find this
2+
3+
import { afterAll, expect, it, vi } from 'vitest'
4+
import { value } from '../src/rely-on-hoisted'
5+
6+
const globalValue = await vi.hoisted(async () => {
7+
// @ts-expect-error not typed global
8+
globalThis.someGlobalValue = 'globalValue'
9+
return 'globalValue'
10+
})
11+
12+
afterAll(() => {
13+
// @ts-expect-error not typed global
14+
delete globalThis.someGlobalValue
15+
})
16+
17+
it('imported value is equal to returned from hoisted', () => {
18+
expect(value).toBe(globalValue)
19+
})
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// this test checks only vi.hoisted because vi.mock affects the regexp to find this
2+
3+
import { afterAll, expect, it, vi } from 'vitest'
4+
import { value } from '../src/rely-on-hoisted'
5+
6+
const globalValue = vi.hoisted(() => {
7+
// @ts-expect-error not typed global
8+
globalThis.someGlobalValue = 'globalValue'
9+
return 'globalValue'
10+
})
11+
12+
afterAll(() => {
13+
// @ts-expect-error not typed global
14+
delete globalThis.someGlobalValue
15+
})
16+
17+
it('imported value is equal to returned from hoisted', () => {
18+
expect(value).toBe(globalValue)
19+
})

0 commit comments

Comments
 (0)