diff --git a/packages/mocker/src/node/hoistMocks.ts b/packages/mocker/src/node/hoistMocks.ts index 1ececc2e63b3..81d012052791 100644 --- a/packages/mocker/src/node/hoistMocks.ts +++ b/packages/mocker/src/node/hoistMocks.ts @@ -107,7 +107,8 @@ export function hoistMocks( } = options // hoist at the start of the file, after the hashbang - let hoistIndex = hashbangRE.exec(code)?.[0].length ?? 0 + const hashbangEnd = hashbangRE.exec(code)?.[0].length ?? 0 + let hoistIndex = hashbangEnd let hoistedModuleImported = false @@ -535,11 +536,12 @@ export function hoistMocks( const utilityImports = [...usedUtilityExports] // "vi" or "vitest" is imported from a module other than "vitest" if (utilityImports.some(name => idToImportMap.has(name))) { - s.prepend(API_NOT_FOUND_CHECK(utilityImports)) + s.appendLeft(hashbangEnd, API_NOT_FOUND_CHECK(utilityImports)) } // if "vi" or "vitest" are not imported at all, import them else if (utilityImports.length) { - s.prepend( + s.appendLeft( + hashbangEnd, `import { ${[...usedUtilityExports].join(', ')} } from ${JSON.stringify( hoistedModule, )}\n`, diff --git a/test/core/test/injector-mock.test.ts b/test/core/test/injector-mock.test.ts index eca95b745938..56c66b36a330 100644 --- a/test/core/test/injector-mock.test.ts +++ b/test/core/test/injector-mock.test.ts @@ -915,21 +915,55 @@ export default (function getRandom() { // #8002 test('with hashbang', () => { expect( - hoistSimpleCodeWithoutMocks( + hoistSimpleCode( `#!/usr/bin/env node +vi.mock('foo'); console.log("it can parse the hashbang")`, ), - ).toMatchInlineSnapshot(`undefined`) + ).toMatchInlineSnapshot(` + "#!/usr/bin/env node + import { vi } from "vitest" + vi.mock('foo'); + console.log("it can parse the hashbang")" + `) }) test('import hoisted after hashbang', () => { expect( - hoistSimpleCodeWithoutMocks( + hoistSimpleCode( `#!/usr/bin/env node +vi.mock('foo'); console.log(foo); import foo from "foo"`, ), - ).toMatchInlineSnapshot(`undefined`) + ).toMatchInlineSnapshot(` + "#!/usr/bin/env node + import { vi } from "vitest" + vi.mock('foo'); + const __vi_import_0__ = await import("foo"); + console.log(__vi_import_0__.default);" + `) + }) + + test('import hoisted after hashbang', () => { + expect( + hoistSimpleCode( + `#!/usr/bin/env node +import { vi } from './proxy' +vi.mock('foo'); +console.log(foo); +import foo from "foo"`, + ), + ).toMatchInlineSnapshot(` + "#!/usr/bin/env node + + if (typeof globalThis["vi"] === "undefined") { throw new Error("There are some problems in resolving the mocks API.\\nYou may encounter this issue when importing the mocks API from another module other than 'vitest'.\\nTo fix this issue you can either:\\n- import the mocks API directly from 'vitest'\\n- enable the 'globals' option") } + __vi_import_0__.vi.mock('foo'); + const __vi_import_0__ = await import("./proxy"); + const __vi_import_1__ = await import("foo"); + + console.log(__vi_import_1__.default);" + `) }) // #10289