Skip to content

Commit

Permalink
fix(vitest): correctly hoist vi.hoisted if assigned (#4285)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Oct 10, 2023
1 parent eac7776 commit ff93a57
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/vitest/src/node/hoistMocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,11 @@ function transformImportSpecifiers(node: ImportDeclaration) {
}

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

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

if (!hasMocks)
return
Expand Down
2 changes: 2 additions & 0 deletions test/core/src/rely-on-hoisted.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// @ts-expect-error not typed global
export const value = globalThis.someGlobalValue
19 changes: 19 additions & 0 deletions test/core/test/hoisted-async-simple.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// this test checks only vi.hoisted because vi.mock affects the regexp to find this

import { afterAll, expect, it, vi } from 'vitest'
import { value } from '../src/rely-on-hoisted'

const globalValue = await vi.hoisted(async () => {
// @ts-expect-error not typed global
globalThis.someGlobalValue = 'globalValue'
return 'globalValue'
})

afterAll(() => {
// @ts-expect-error not typed global
delete globalThis.someGlobalValue
})

it('imported value is equal to returned from hoisted', () => {
expect(value).toBe(globalValue)
})
19 changes: 19 additions & 0 deletions test/core/test/hoisted-simple.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// this test checks only vi.hoisted because vi.mock affects the regexp to find this

import { afterAll, expect, it, vi } from 'vitest'
import { value } from '../src/rely-on-hoisted'

const globalValue = vi.hoisted(() => {
// @ts-expect-error not typed global
globalThis.someGlobalValue = 'globalValue'
return 'globalValue'
})

afterAll(() => {
// @ts-expect-error not typed global
delete globalThis.someGlobalValue
})

it('imported value is equal to returned from hoisted', () => {
expect(value).toBe(globalValue)
})

0 comments on commit ff93a57

Please sign in to comment.