| | |

Vitest 25 🧪 Browser Mode — Stable in v4, Playwright/WebdriverIO providers

⏱️ Estimated read: 8 min | |

Vitest Browser Mode executes component and unit test files inside real browser engines instead of emulated headless environments like JSDOM or Happy DOM. Reaching stable status in Vitest 4, Browser Mode eliminates brittle DOM workarounds by leveraging native layout engines, real CSS rendering, authentic pointer events, and clipboard interactions.

Execution relies on a dedicated driver provider—either Playwright or WebdriverIO—which manages real browser instances while Vitest serves source files through Vite’s lightning-fast development server.

Why X exists

The JSDOM simulation gap.

Emulated DOM environments like JSDOM lack layout engines, making it impossible to accurately test layout calculations, CSS media queries, scrolling behavior, or element bounding rects.

The flaky headless E2E overhead.

Traditional end-to-end frameworks require full application deployment and heavy orchestration layers, making them too slow for rapid component-level test loops.

The browser fidelity requirement.

Modern web applications depend heavily on native browser APIs, pointer event semantics, focus management, and accessibility trees that simulated environments cannot replicate authentically.

The fragmented test runner problem.

Developers previously had to maintain entirely separate test runners (like Playwright Test or Cypress) alongside Vitest just to verify component interactions inside real browsers.

The unified Vite transformation pipeline.

Teams wanted to leverage Vite’s hot module reload (HMR) speed, shared configuration plugins, and standard expect assertions inside genuine browser contexts.

a. Configuring Browser Mode with the Playwright Provider

To activate Browser Mode in Vitest 4+, install the browser package along with the Playwright provider plugin, then configure your test settings inside vitest.config.ts.

Bash

npm install -D vitest @vitest/browser @vitest/browser-playwright playwright

TypeScript

// vitest.config.ts
import { defineConfig } from 'vitest/config';
import { playwright } from '@vitest/browser-playwright';

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: playwright(),
      // Define target browser instances for execution
      instances: [
        { browser: 'chromium' },
        { browser: 'firefox' },
      ],
      headless: true,
    },
  },
});

The configuration imports the playwright factory function and declares an instances array, enabling parallel test execution across multiple genuine browser engines from a single command invocation.

b. Selecting Alternative Providers: WebdriverIO Integration

If your infrastructure relies on WebdriverIO rather than Playwright, Vitest provides an equivalent provider package (@vitest/browser-webdriverio) that supports standard WebDriver-compliant browsers and remote grids.

Bash

npm install -D vitest @vitest/browser @vitest/browser-webdriverio

TypeScript

// vitest.config.ts
import { defineConfig } from 'vitest/config';
import { webdriverio } from '@vitest/browser-webdriverio';

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: webdriverio(),
      instances: [
        { browser: 'chrome' },
        { browser: 'edge' },
      ],
      headless: true,
    },
  },
});

Switching providers requires changing only the imported provider factory and installing the corresponding driver package, keeping your test assertions and interaction APIs completely uniform.

c. Writing Component Interactions with Page and UserEvent APIs

Vitest Browser Mode exposes an ergonomic interaction context (@vitest/browser/context) containing robust locators, asynchronous action helpers, and realistic user event simulations.

TypeScript

// src/components/counter.test.ts
import { describe, expect, it } from 'vitest';
import { page, userEvent } from '@vitest/browser/context';
import { render } from 'vitest-browser-react';
import { Counter } from './Counter.tsx';

describe('Counter Component Browser Suite', () => {
  it('increments counter value on button click', async () => {
    // Render component into real browser DOM via framework adapter
    render(<Counter initialCount={0} />);

    // Query element using accessible testing library locators
    const button = page.getByRole('button', { name: /increment/i });
    const output = page.getByTestId('counter-value');

    await expect.element(output).toHaveTextContent('0');

    // Perform realistic pointer interactions using userEvent
    await userEvent.click(button);

    await expect.element(output).toHaveTextContent('1');
  });
});

The page object provides strict element locators, while userEvent dispatches authentic pointer and keyboard sequences, ensuring components respond to inputs exactly as they would for real users in production.

Complete Example Session

TypeScript

// ============================================
// PART 1: CONFIGURATION SETUP (vitest.config.ts)
// ============================================
import { defineConfig } from 'vitest/config';
import { playwright } from '@vitest/browser-playwright';

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: playwright(),
      instances: [{ browser: 'chromium' }],
      headless: true,
    },
  },
});

TypeScript

// ============================================
// PART 2: PACKAGE MANIFEST SCRIPTS
// ============================================
export const packageManifestScripts = {
  "scripts": {
    "test:browser": "vitest --browser",
    "test:headless": "vitest run --browser.headless"
  }
};

TypeScript

// ============================================
// PART 3: TARGET COMPONENT IMPLEMENTATION (LoginForm.tsx)
// ============================================
import React, { useState } from 'react';

export function LoginForm({ onSubmit }: { onSubmit: (u: string) => void }) {
  const [username, setUsername] = useState('');
  return (
    <form onSubmit={(e) => { e.preventDefault(); onSubmit(username); }}>
      <label htmlFor="username">Username</label>
      <input id="username" value={username} onChange={(e) => setUsername(e.target.value)} />
      <button type="submit">Submit</button>
    </form>
  );
}

TypeScript

// ============================================
// PART 4: BROWSER TEST IMPORT CONTEXT
// ============================================
import { describe, expect, it, vi } from 'vitest';
import { page, userEvent } from '@vitest/browser/context';
import { render } from 'vitest-browser-react';

TypeScript

// ============================================
// PART 5: RENDERING COMPONENT IN BROWSER CONTEXT
// ============================================
describe('LoginForm Browser Interaction', () => {
  it('submits form with typed username value', async () => {
    const handleSubmit = vi.fn();
    render(<LoginForm onSubmit={handleSubmit} />);

TypeScript

// ============================================
// PART 6: LOCATING FORM CONTROLS
// ============================================
    const inputField = page.getByRole('textbox', { name: /username/i });
    const submitButton = page.getByRole('button', { name: /submit/i });

TypeScript

// ============================================
// PART 7: SIMULATING REAL USER INPUT
// ============================================
    await userEvent.fill(inputField, 'alex_dev');
    await userEvent.click(submitButton);

TypeScript

// ============================================
// PART 8: ASSERTING CALLBACK INTERACTIONS
// ============================================
    expect(handleSubmit).toHaveBeenCalledWith('alex_dev');
  });
});

TypeScript

// ============================================
// PART 9: SCREENSHOT CAPTURE VALIDATION
// ============================================
describe('Visual State Verification', () => {
  it('captures element screenshot for visual regression check', async () => {
    render(<LoginForm onSubmit={() => {}} />);
    const formElement = page.getByRole('textbox');
    await expect.element(formElement).toMatchScreenshot();
  });
});

TypeScript

// ============================================
// PART 10: SESSION FINALIZATION
// ============================================
// Browser Mode execution session completed successfully across all test files

Quick Reference

Browser Configuration Options

PropertyTarget ScopePurpose
enabledtest.browserMaster switch activating Browser Mode
providertest.browserSelects driver factory (playwright() or webdriverio())
instancestest.browserArray defining target browser engines (chromium, firefox, webkit)
headlesstest.browserToggles visible browser windows vs. background execution

Interaction API Methods

UtilitySourceFunctionality
page.getByRole(...)@vitest/browser/contextLocates elements using accessibility roles
userEvent.click(...)@vitest/browser/contextDispatches realistic pointer click events
userEvent.fill(...)@vitest/browser/contextTypes text into input fields naturally
expect.element(...)Vitest Browser AssertionsAsserts DOM state, visibility, and text content

Best Practices

✅ Do This:

TypeScript

provider: playwright()                                                      // ✅

❌ Don’t Do This:

TypeScript

// attempt to run browser tests without declaring an explicit provider      // ❌

✅ Do This:

TypeScript

instances: [{ browser: 'chromium' }, { browser: 'firefox' }]                // ✅

❌ Don’t Do This:

TypeScript

// rely on un-isolated shared global state across different browser files   // ❌

✅ Do This:

TypeScript

await userEvent.click(page.getByRole('button'));                            // ✅

❌ Don’t Do This:

TypeScript

element.click(); // bypassing userEvent simulation for native events        // ❌

Common Pitfalls

PitfallWhy It HappensFix
Browser launch failure in CI environmentsMissing underlying system dependencies or browser binariesRun npx playwright install --with-deps in your CI build workflow
Strict mode locator violation errorsA query selector matches multiple elements on the page simultaneouslyRefine locators using unique accessibility roles, names, or test IDs
Test hanging indefinitely during startupForgetting to install the specific provider package (@vitest/browser-playwright)Install the required provider dependency matching your configuration
Slow test suite executionRunning large suites of pure logic and reducers in Browser Mode instead of JSDOMReserve Browser Mode strictly for DOM-heavy components and use JSDOM for unit logic

Real-World Examples

1. Configuring Playwright Provider with Chromium and WebKit

TypeScript

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: playwright(),
      instances: [{ browser: 'chromium' }, { browser: 'webkit' }],
    },
  },
});

2. Configuring WebdriverIO Provider for Firefox

TypeScript

export default defineConfig({
  test: {
    browser: {
      enabled: true,
      provider: webdriverio(),
      instances: [{ browser: 'firefox' }],
    },
  },
});

3. Executing Browser Tests in Headless Mode via CLI

Bash

npx vitest run --browser.headless

4. Locating Elements by Test ID in Component Tests

TypeScript

const submitBtn = page.getByTestId('submit-btn');

5. Simulating Keyboard Typing via UserEvent

TypeScript

await userEvent.type(page.getByRole('textbox'), 'SecurePassword123!');

6. Asserting Element Visibility State

TypeScript

await expect.element(page.getByText('Loading...')).toBeVisible();

7. Handling Asynchronous Element Appearance

TypeScript

await expect.element(page.getByRole('alert')).toBeInTheDocument();

8. Installing Playwright Binaries with System Dependencies in CI

YAML

- name: Install Playwright Browsers
  run: npx playwright install --with-deps chromium

9. Setting Custom Viewport Dimensions in Config

TypeScript

instances: [
  { browser: 'chromium', viewport: { width: 1280, height: 720 } }
]

10. Capturing Visual Regression Snapshots in Browser Mode

TypeScript

await expect.element(page.getByTestId('card')).toMatchSnapshot();

Visual

Browser Mode Architecture

┌────────────────────────────────────────────────────────┐
│  Vitest Test Runner Process                            │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│  Vite Dev Server (Serves modules via native ESM)       │
└───────────────────────────┬────────────────────────────┘
                            │
            ┌───────────────┴───────────────┐
            ▼                               ▼
┌───────────────────────┐       ┌───────────────────────┐
│ Playwright Provider   │       │ WebdriverIO Provider  │
│ (Chromium/Firefox)    │       │ (Chrome/Edge/Safari)  │
└───────────────────────┘       └───────────────────────┘

JSDOM vs. Browser Mode Execution Flow

┌────────────────────────────────────────────────────────┐
│ JSDOM: Node.js Process + Simulated Node DOM Engine     │
└────────────────────────────────────────────────────────┘

┌────────────────────────────────────────────────────────┐
│ BROWSER MODE: Node.js + Vite Dev Server + Real Browser │
└────────────────────────────────────────────────────────┘

Interaction API Lifecycle

┌────────────────────────────────────────────────────────┐
│ render(<Component />) ──► Mounts inside Real Browser   │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│ page.getByRole() ──► Locates Element via Accessibility │
└───────────────────────────┬────────────────────────────┘
                            │
                            ▼
┌────────────────────────────────────────────────────────┐
│ userEvent.click() ──► Dispatches Authentic Events      │
└────────────────────────────────────────────────────────┘

Summary

ItemValue
ConceptReal-Browser Testing in Vitest (Stable in v4)
Core ProvidersPlaywright (@vitest/browser-playwright) or WebdriverIO (@vitest/browser-webdriverio)
Master Activationtest.browser: { enabled: true, provider: ... }
Target Instancesinstances array defining browser engines (chromium, firefox, webkit)
Interaction Toolkitpage (locators) and userEvent (realistic simulation)
Primary BenefitEliminates JSDOM simulation gaps with real layout and CSS rendering
CI ExecutionHeadless mode via --browser.headless flag
Binary InstallationRequires driver binaries (npx playwright install --with-deps)
Assertion Modelexpect.element(...) for browser-native DOM validations
Framework SupportReact, Vue, Svelte via official rendering adapters

Key takeaways:

  • Adopt stable Browser Mode. Transition DOM-heavy component tests to Vitest Browser Mode (stable in v4+) to run code inside authentic browser engines.
  • Choose your driver provider. Select either Playwright (recommended for parallel speed and easy binary management) or WebdriverIO.
  • Configure multi-browser instances. Define target engines (chromium, firefox, webkit) inside the instances array for cross-browser validation.
  • Leverage realistic interactions. Use userEvent instead of synthetic dispatch methods to simulate authentic pointer and keyboard events.
  • Maintain JSDOM for pure logic. Keep lightweight unit tests and pure functions in fast JSDOM environments while reserving Browser Mode for UI components.
  • Automate CI readiness. Ensure headless flags and browser binaries with system dependencies are provisioned correctly in your continuous integration workflows.

Remember: Vitest Browser Mode bridges the gap between fast unit testing and authentic browser validation. By combining Vite’s instant HMR transformation pipeline with Playwright or WebdriverIO execution drivers, engineering teams can verify component behavior under real rendering engines with zero configuration friction.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!