diff --git a/packages/vitest/src/node/hoistMocks.ts b/packages/vitest/src/node/hoistMocks.ts index 515329bfa4e1..8be08c13620a 100644 --- a/packages/vitest/src/node/hoistMocks.ts +++ b/packages/vitest/src/node/hoistMocks.ts @@ -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 diff --git a/test/core/src/rely-on-hoisted.ts b/test/core/src/rely-on-hoisted.ts new file mode 100644 index 000000000000..c1c9bf0a2d95 --- /dev/null +++ b/test/core/src/rely-on-hoisted.ts @@ -0,0 +1,2 @@ +// @ts-expect-error not typed global +export const value = globalThis.someGlobalValue diff --git a/test/core/test/hoisted-async-simple.test.ts b/test/core/test/hoisted-async-simple.test.ts new file mode 100644 index 000000000000..712be235170c --- /dev/null +++ b/test/core/test/hoisted-async-simple.test.ts @@ -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) +}) diff --git a/test/core/test/hoisted-simple.test.ts b/test/core/test/hoisted-simple.test.ts new file mode 100644 index 000000000000..a60759fa634e --- /dev/null +++ b/test/core/test/hoisted-simple.test.ts @@ -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) +})