diff --git a/packages/vitest/src/node/plugins/mock.ts b/packages/vitest/src/node/plugins/mock.ts index 9310941dfef6..1267ac548fee 100644 --- a/packages/vitest/src/node/plugins/mock.ts +++ b/packages/vitest/src/node/plugins/mock.ts @@ -33,6 +33,13 @@ export function hoistMocks(code: string) { return m } +const API_NOT_FOUND_ERROR = `There are some problems in resolving the mocks API. +You may encounter this issue when importing the mocks API from another module other than 'vitest'. + +To fix this issue you can either: +- import the mocks API directly from 'vitest' +- enable the 'globals' options` + export const MocksPlugin = (): Plugin => { return { name: 'vitest:mock-plugin', @@ -43,12 +50,22 @@ export const MocksPlugin = (): Plugin => { if (m) { // hoist vitest imports in case it was used inside vi.mock factory #425 const vitestImports = code.matchAll(vitestRegexp) + let found = false + for (const match of vitestImports) { const indexStart = match.index! const indexEnd = match[0].length + indexStart m.remove(indexStart, indexEnd) m.prepend(`${match[0]}\n`) + found = true } + + // if no vitest import found, check if the mock API is reachable after the hoisting + if (!found) { + m.prepend('try { vi } catch (_) { try { vitest } catch (__)' + + `{ throw new Error(${JSON.stringify(API_NOT_FOUND_ERROR)}) } }\n`) + } + return { code: m.toString(), map: m.generateMap({ hires: true }), diff --git a/test/fails/fixtures/mock-import-proxy-module.test.ts b/test/fails/fixtures/mock-import-proxy-module.test.ts new file mode 100644 index 000000000000..a92f9e8f139a --- /dev/null +++ b/test/fails/fixtures/mock-import-proxy-module.test.ts @@ -0,0 +1,8 @@ +import { expect, test, vi } from './proxy-module' + +// This can be used only when imported directly from vitest +vi.mock('vite') + +test('hi', () => { + expect(1 + 1).toEqual(2) +}) diff --git a/test/fails/fixtures/proxy-module.ts b/test/fails/fixtures/proxy-module.ts new file mode 100644 index 000000000000..181c011768f3 --- /dev/null +++ b/test/fails/fixtures/proxy-module.ts @@ -0,0 +1 @@ +export * from 'vitest' diff --git a/test/fails/test/__snapshots__/runner.test.ts.snap b/test/fails/test/__snapshots__/runner.test.ts.snap index fc01ca968991..532fa9c7520e 100644 --- a/test/fails/test/__snapshots__/runner.test.ts.snap +++ b/test/fails/test/__snapshots__/runner.test.ts.snap @@ -6,6 +6,8 @@ exports[`should fails > expect.test.ts > expect.test.ts 1`] = `"AssertionError: exports[`should fails > hook-timeout.test.ts > hook-timeout.test.ts 1`] = `"Error: Hook timed out in 10ms."`; +exports[`should fails > mock-import-alias.test.ts > mock-import-alias.test.ts 1`] = `"Error: There are some problems in resolving the mocks API."`; + exports[`should fails > nested-suite.test.ts > nested-suite.test.ts 1`] = `"AssertionError: expected true to be false // Object.is equality"`; exports[`should fails > stall.test.ts > stall.test.ts 1`] = `"TypeError: failure"`;