vitest-dev/vitest · error · Error

vitest/browser can be imported only inside the Browser Mode.

Error message

vitest/browser can be imported only inside the Browser Mode. Instead, it was imported outside of Vitest.

What it means

Same module-level guard as error 167, but this branch fires when globalThis.__vitest_worker__ is absent entirely (no Vitest worker context), meaning vitest/browser was imported outside of any Vitest run — e.g. imported directly by Node, by a plain script, or during SSR/build of an application that bundled the test entry.

Source

Thrown at packages/vitest/browser/context.js:14

// Vitest resolves "vitest/browser" as a virtual module instead

// fake exports for static analysis
export const page = null
export const server = null
export const userEvent = null
export const cdp = null
export const commands = null
export const locators = null
export const utils = null

const pool = globalThis.__vitest_worker__?.ctx?.pool

throw new Error(
  // eslint-disable-next-line prefer-template
  'vitest/browser can be imported only inside the Browser Mode. '
  + (pool
    ? `Your test is running in ${pool} pool. Make sure your regular tests are excluded from the "test.include" glob pattern.`
    : 'Instead, it was imported outside of Vitest.'),
)

View on GitHub (pinned to 1fa9837ec2)

Solutions

  1. Ensure vitest/browser is only imported from files collected by Vitest's browser pool, never from app or build code.
  2. Exclude test directories from your bundler/build entry points.
  3. Run test files through the vitest CLI, not node/tsx directly.

Example fix

// before — app code transitively imports a helper that imports vitest/browser

// after — split test-only helpers into a separate module the app never imports,
// or guard the import:
if (import.meta.env?.MODE === 'test') {
  const { page } = await import('vitest/browser')
}
Defensive patterns

Strategy: validation

Validate before calling

const ctx = globalThis.__vitest_worker__
if (!ctx?.ctx?.pool) {
  // not inside Vitest — do not import vitest/browser
}

Type guard

function isInsideVitestWorker(): boolean {
  return !!globalThis.__vitest_worker__?.ctx
}

Prevention

When it happens

Trigger: Importing vitest/browser in a non-test context: a production build that accidentally includes test files, a Node script that imports a test helper, or a bundler resolving vitest/browser during app compilation.

Common situations: Test files leaking into the production build glob; a shared utility imported by both app code and tests that pulls in vitest/browser; running test files with plain node/tsx instead of vitest.

Related errors


AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11). Data as JSON: /api/errors/8178f198e657f172. Report an issue: GitHub.