Browser runner for Vitest enabling tests to run in actual browser environments with real DOM APIs and browser-specific features
npx @tessl/cli install tessl/npm-vitest--browser@3.2.00
# @vitest/browser
1
2
@vitest/browser is a browser runner for Vitest that enables tests to run in actual browser environments rather than in Node.js. It provides comprehensive testing capabilities with real DOM APIs, browser-specific features, and multiple automation providers including Playwright and WebdriverIO, allowing developers to test frontend applications in real browser contexts with full interaction simulation and cross-browser compatibility.
3
4
## Package Information
5
6
- **Package Name**: @vitest/browser
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @vitest/browser`
10
11
## Core Imports
12
13
Browser context API (client-side):
14
15
```typescript
16
import { userEvent, page, commands, server, locators, cdp } from "@vitest/browser/context";
17
```
18
19
Server-side API (Node.js):
20
21
```typescript
22
import { createBrowserServer, createBrowserPool, distRoot } from "@vitest/browser";
23
```
24
25
Provider imports:
26
27
```typescript
28
import { playwright, webdriverio, preview } from "@vitest/browser/providers";
29
```
30
31
Utilities and matchers:
32
33
```typescript
34
import { debug, prettyDOM, getElementError, getElementLocatorSelectors } from "@vitest/browser/utils";
35
import "@vitest/browser/matchers";
36
```
37
38
## Basic Usage
39
40
```typescript
41
import { userEvent, page } from "@vitest/browser/context";
42
import { expect } from "vitest";
43
44
// Test with user interactions
45
test("form submission", async () => {
46
// Find elements using locators
47
const input = page.getByLabelText("Username");
48
const button = page.getByRole("button", { name: "Submit" });
49
50
// Simulate user interactions
51
await userEvent.fill(input, "testuser");
52
await userEvent.click(button);
53
54
// Assert results
55
await expect.element(page.getByText("Welcome testuser")).toBeVisible();
56
});
57
58
// Take screenshots
59
test("visual test", async () => {
60
const screenshot = await page.screenshot();
61
expect(screenshot).toMatchImageSnapshot();
62
});
63
64
// File system operations
65
import { commands } from "@vitest/browser/context";
66
67
test("config file test", async () => {
68
const config = await commands.readFile("./config.json");
69
const parsed = JSON.parse(config);
70
expect(parsed.version).toBe("1.0.0");
71
});
72
```
73
74
## Architecture
75
76
@vitest/browser is built around several key components:
77
78
- **Provider System**: Pluggable browser automation using Playwright, WebdriverIO, or preview mode
79
- **Context API**: Client-side testing environment with user interaction capabilities
80
- **Locator System**: CSS and accessibility-based element location with powerful filtering
81
- **Command Bridge**: Server-side file system operations accessible from browser context
82
- **Type Safety**: Full TypeScript integration with provider-specific type augmentations
83
84
## Capabilities
85
86
### Context API
87
88
Client-side testing environment providing user interaction simulation, element location, and browser-specific utilities. The main interface for writing browser tests.
89
90
```typescript { .api }
91
const userEvent: UserEvent;
92
const page: BrowserPage;
93
const commands: BrowserCommands;
94
const server: ServerInfo;
95
const locators: BrowserLocators;
96
function cdp(): CDPSession;
97
```
98
99
[Browser Context](./context.md)
100
101
### Locator System
102
103
Powerful element location system supporting CSS selectors, accessibility queries, chaining, and filtering for robust element targeting.
104
105
```typescript { .api }
106
interface Locator {
107
getByRole(role: string, options?: LocatorByRoleOptions): Locator;
108
getByText(text: string | RegExp, options?: LocatorOptions): Locator;
109
getByTestId(testId: string | RegExp): Locator;
110
click(options?: UserEventClickOptions): Promise<void>;
111
element(): Element;
112
}
113
```
114
115
[Locators](./locators.md)
116
117
### User Interactions
118
119
Comprehensive user event simulation supporting keyboard input, mouse interactions, form manipulation, and file uploads with provider-specific implementations.
120
121
```typescript { .api }
122
interface UserEvent {
123
click(element: Element | Locator, options?: UserEventClickOptions): Promise<void>;
124
type(element: Element | Locator, text: string, options?: UserEventTypeOptions): Promise<void>;
125
fill(element: Element | Locator, text: string, options?: UserEventFillOptions): Promise<void>;
126
keyboard(text: string): Promise<void>;
127
}
128
```
129
130
[User Interactions](./interactions.md)
131
132
### Provider System
133
134
Browser automation providers for running tests in different browser environments, each with specific capabilities and configuration options.
135
136
```typescript { .api }
137
const playwright: BrowserProviderModule;
138
const webdriverio: BrowserProviderModule;
139
const preview: BrowserProviderModule;
140
```
141
142
[Providers](./providers.md)
143
144
### Server Integration
145
146
Node.js server-side functionality for creating browser test environments and managing browser pools in test suites.
147
148
```typescript { .api }
149
function createBrowserServer(
150
project: TestProject,
151
configFile: string | undefined,
152
prePlugins?: Plugin[],
153
postPlugins?: Plugin[]
154
): Promise<ParentBrowserProject>;
155
156
function createBrowserPool(vitest: Vitest): ProcessPool;
157
158
const distRoot: string;
159
```
160
161
[Server Integration](./server.md)
162
163
### File System Commands
164
165
Server-side file operations accessible from browser context for reading configuration files, test fixtures, and writing test outputs.
166
167
```typescript { .api }
168
interface BrowserCommands {
169
readFile(path: string, options?: BufferEncoding | FsOptions): Promise<string>;
170
writeFile(path: string, content: string, options?: FsOptions): Promise<void>;
171
removeFile(path: string): Promise<void>;
172
}
173
```
174
175
[File System Commands](./commands.md)
176
177
### Utilities and Debugging
178
179
Development tools for debugging element queries, DOM inspection, and test development with pretty-printing and error formatting.
180
181
```typescript { .api }
182
function debug(element?: Element | Locator | null | (Element | Locator)[], maxLength?: number, options?: PrettyDOMOptions): void;
183
function prettyDOM(dom?: Element | Locator | undefined | null, maxLength?: number, options?: PrettyDOMOptions): string;
184
function getElementError(selector: string, container?: Element): Error;
185
function getElementLocatorSelectors(element: Element): LocatorSelectors;
186
```
187
188
[Utilities](./utilities.md)
189
190
### Enhanced Assertions
191
192
DOM-specific matchers extending Vitest's expect API with browser-aware assertions and element polling for reliable test assertions.
193
194
```typescript { .api }
195
interface ExpectStatic {
196
element<T extends Element | Locator | null>(element: T, options?: ExpectPollOptions): PromisifyDomAssertion<Awaited<Element | null>>;
197
}
198
```
199
200
[Enhanced Assertions](./assertions.md)
201
202
## Types
203
204
Core type definitions used across the API:
205
206
```typescript { .api }
207
interface LocatorOptions {
208
exact?: boolean;
209
hasText?: string | RegExp;
210
hasNotText?: string | RegExp;
211
has?: Locator;
212
hasNot?: Locator;
213
}
214
215
interface ScreenshotOptions {
216
element?: Element | Locator;
217
path?: string;
218
base64?: boolean;
219
save?: boolean;
220
}
221
222
type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'utf-16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex';
223
224
interface ServerInfo {
225
platform: string;
226
version: string;
227
provider: string;
228
browser: string;
229
commands: BrowserCommands;
230
config: SerializedConfig;
231
}
232
233
interface BrowserLocators {
234
createElementLocators(element: Element): LocatorSelectors;
235
extend(methods: Record<string, Function>): void;
236
}
237
238
interface CDPSession {
239
// Methods are defined by the provider type augmentation
240
}
241
242
type ARIARole =
243
// Widget roles
244
| "button" | "checkbox" | "gridcell" | "link" | "menuitem" | "menuitemcheckbox"
245
| "menuitemradio" | "option" | "progressbar" | "radio" | "scrollbar" | "searchbox"
246
| "slider" | "spinbutton" | "switch" | "tab" | "tabpanel" | "textbox" | "treeitem"
247
// Composite widget roles
248
| "combobox" | "grid" | "listbox" | "menu" | "menubar" | "radiogroup" | "tablist" | "tree" | "treegrid"
249
// Document structure roles
250
| "application" | "article" | "blockquote" | "caption" | "cell" | "columnheader" | "definition"
251
| "deletion" | "directory" | "document" | "emphasis" | "feed" | "figure" | "generic" | "group"
252
| "heading" | "img" | "insertion" | "list" | "listitem" | "math" | "meter" | "none" | "note"
253
| "paragraph" | "presentation" | "row" | "rowgroup" | "rowheader" | "separator" | "strong"
254
| "subscript" | "superscript" | "table" | "term" | "time" | "toolbar" | "tooltip"
255
// Landmark roles
256
| "banner" | "complementary" | "contentinfo" | "form" | "main" | "navigation" | "region" | "search"
257
// Live region roles
258
| "alert" | "log" | "marquee" | "status" | "timer"
259
// Window roles
260
| "alertdialog" | "dialog"
261
// Uncategorized roles
262
| "code";
263
```