Browser runner for Vitest enabling tests to run in actual browser environments with real DOM APIs and browser-specific features
—
Node.js server-side functionality for creating browser test environments and managing browser pools in test suites, providing the infrastructure for running browser tests.
Create and configure browser test servers for Vitest test execution.
/**
* Creates a browser server instance for running tests
* @param project - Vitest test project instance
* @param configFile - Optional path to Vite config file
* @param prePlugins - Plugins to add before default plugins
* @param postPlugins - Plugins to add after default plugins
* @returns Promise resolving to ParentBrowserProject instance
*/
function createBrowserServer(
project: TestProject,
configFile: string | undefined,
prePlugins?: Plugin[],
postPlugins?: Plugin[]
): Promise<ParentBrowserProject>;Usage Examples:
import { createBrowserServer } from "@vitest/browser";
import type { TestProject, Plugin } from "vitest/node";
// Basic browser server creation
async function setupBrowserTests(project: TestProject) {
const browserServer = await createBrowserServer(
project,
undefined // Use default config
);
return browserServer;
}
// With custom plugins
const customPlugin: Plugin = {
name: 'custom-plugin',
configureServer(server) {
// Custom server configuration
}
};
const browserServer = await createBrowserServer(
project,
'./vitest.config.ts',
[customPlugin], // Pre-plugins
[] // Post-plugins
);Create and manage pools of browser instances for parallel test execution.
/**
* Creates a browser test pool for managing multiple browser instances
* @param vitest - Vitest instance for test execution
* @returns ProcessPool instance for parallel test execution
*/
function createBrowserPool(vitest: Vitest): ProcessPool;Usage Examples:
import { createBrowserPool } from "@vitest/browser";
import type { Vitest } from "vitest/node";
// Create browser pool for parallel testing
function setupBrowserPool(vitest: Vitest) {
const browserPool = createBrowserPool(vitest);
return browserPool;
}
// Pool is typically managed internally by Vitest
// but can be used for custom test orchestrationInterface for browser-specific project configuration and management.
/**
* Browser project interface for configuration and test management
*/
interface ProjectBrowser {
// Project browser implementation details
// (specific properties depend on internal implementation)
}Path constant for accessing browser package distribution files.
/**
* Path to the distribution directory of @vitest/browser package
*/
const distRoot: string;Usage Examples:
import { distRoot } from "@vitest/browser";
import { join } from "path";
// Access client-side assets
const clientScriptPath = join(distRoot, "client.js");
const locatorScriptPath = join(distRoot, "locators", "index.js");
// Useful for custom plugin development
function customBrowserPlugin() {
return {
name: 'custom-browser-plugin',
configureServer(server) {
// Serve additional browser assets
server.middlewares.use('/browser-assets', express.static(distRoot));
}
};
}The browser server handles several key responsibilities:
Vite Server Integration:
Provider Integration:
Mocker Registry:
Plugin System:
Custom Plugin Development:
import { createBrowserServer } from "@vitest/browser";
import type { Plugin } from "vite";
// Custom plugin for browser tests
const browserTestPlugin: Plugin = {
name: 'browser-test-plugin',
configureServer(server) {
// Add custom middleware
server.middlewares.use('/api', (req, res, next) => {
// Handle test API requests
if (req.url?.startsWith('/api/test-data')) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ data: 'test' }));
} else {
next();
}
});
},
buildStart() {
// Setup test environment
console.log('Browser test environment starting...');
}
};
// Use plugin with browser server
const browserServer = await createBrowserServer(
project,
configFile,
[browserTestPlugin]
);Environment Configuration:
// vitest.config.ts - Server-side configuration
export default defineConfig({
test: {
browser: {
enabled: true,
provider: 'playwright',
name: 'chromium',
// Server-side options
providerOptions: {
launch: {
headless: process.env.CI === 'true',
devtools: !process.env.CI
}
}
}
},
server: {
// Vite server options for browser tests
port: 3000,
host: true,
fs: {
// Allow serving files from test fixtures
allow: ['..']
}
}
});Test Project Integration:
import { createBrowserServer } from "@vitest/browser";
import type { TestProject } from "vitest/node";
class CustomTestRunner {
private browserServer?: ParentBrowserProject;
async setup(project: TestProject) {
// Create browser server with project configuration
this.browserServer = await createBrowserServer(project, project.config.configFile);
// Server is now ready for browser tests
console.log(`Browser server ready on port ${this.browserServer.port}`);
}
async runTests() {
if (!this.browserServer) {
throw new Error('Browser server not initialized');
}
// Run tests using the browser server
// (typically handled by Vitest internally)
}
async cleanup() {
if (this.browserServer) {
await this.browserServer.close();
}
}
}Common server-side error scenarios and handling:
import { createBrowserServer } from "@vitest/browser";
try {
const browserServer = await createBrowserServer(project, configFile);
} catch (error) {
if (error.message.includes('version mismatch')) {
console.error('Vitest and @vitest/browser versions do not match');
// Handle version compatibility issues
} else if (error.message.includes('port already in use')) {
console.error('Server port is already in use');
// Handle port conflicts
} else {
console.error('Failed to create browser server:', error);
// Handle other server creation errors
}
}The server API is typically used internally by Vitest, but understanding it helps with:
Custom Test Environments:
// Custom environment that uses browser server
export default class BrowserTestEnvironment implements Environment {
private browserServer?: ParentBrowserProject;
async setup(project: TestProject) {
this.browserServer = await createBrowserServer(project);
// Environment is ready
}
}Plugin Development:
// Vitest plugin that enhances browser testing
function vitestBrowserPlugin(): Plugin {
return {
name: 'vitest-browser-plugin',
config(config) {
// Modify browser test configuration
if (config.test?.browser?.enabled) {
// Add browser-specific settings
}
}
};
}Server-side type definitions:
interface ParentBrowserProject {
// Internal browser project implementation
// Handles browser test orchestration and lifecycle
}
interface BrowserPool {
// Internal browser pool implementation
// Manages multiple browser instances for parallel testing
}Install with Tessl CLI
npx tessl i tessl/npm-vitest--browser