0
# Browser Context
1
2
Client-side testing environment providing the core API for browser tests including user interaction simulation, element location, server communication, and browser-specific utilities.
3
4
## Capabilities
5
6
### UserEvent Object
7
8
Handler for user interactions with comprehensive support for keyboard, mouse, and form manipulation across different browser providers.
9
10
```typescript { .api }
11
/**
12
* Handler for user interactions. The support is provided by the browser provider (playwright or webdriverio).
13
* If used with preview provider, fallbacks to simulated events via @testing-library/user-event.
14
*/
15
const userEvent: UserEvent;
16
17
interface UserEvent {
18
/** Creates a new user event instance with separate keyboard state */
19
setup(): UserEvent;
20
/** Cleans up the user event instance, releasing any resources */
21
cleanup(): Promise<void>;
22
23
/** Click on an element using provider's API */
24
click(element: Element | Locator, options?: UserEventClickOptions): Promise<void>;
25
/** Triggers a double click event on an element */
26
dblClick(element: Element | Locator, options?: UserEventDoubleClickOptions): Promise<void>;
27
/** Triggers a triple click event on an element */
28
tripleClick(element: Element | Locator, options?: UserEventTripleClickOptions): Promise<void>;
29
30
/** Type text on the keyboard (supports user-event keyboard syntax like {Shift}) */
31
keyboard(text: string): Promise<void>;
32
/** Types text into an element (slower but supports keyboard syntax) */
33
type(element: Element | Locator, text: string, options?: UserEventTypeOptions): Promise<void>;
34
/** Fills an input element with text (faster, no keyboard syntax support) */
35
fill(element: Element | Locator, text: string, options?: UserEventFillOptions): Promise<void>;
36
/** Removes all text from an element */
37
clear(element: Element | Locator, options?: UserEventClearOptions): Promise<void>;
38
39
/** Choose one or more values from a select element */
40
selectOptions(
41
element: Element,
42
values: HTMLElement | HTMLElement[] | Locator | Locator[] | string | string[],
43
options?: UserEventSelectOptions
44
): Promise<void>;
45
46
/** Hovers over an element */
47
hover(element: Element | Locator, options?: UserEventHoverOptions): Promise<void>;
48
/** Moves cursor position to the body element */
49
unhover(element: Element | Locator, options?: UserEventHoverOptions): Promise<void>;
50
51
/** Change a file input element to have the specified files */
52
upload(element: Element | Locator, files: File | File[] | string | string[], options?: UserEventUploadOptions): Promise<void>;
53
54
/** Drags a source element on top of the target element */
55
dragAndDrop(source: Element | Locator, target: Element | Locator, options?: UserEventDragAndDropOptions): Promise<void>;
56
57
/** Sends a Tab key event */
58
tab(options?: UserEventTabOptions): Promise<void>;
59
60
/** Copies the selected content */
61
copy(): Promise<void>;
62
/** Cuts the selected content */
63
cut(): Promise<void>;
64
/** Pastes the copied or cut content */
65
paste(): Promise<void>;
66
}
67
```
68
69
**Usage Examples:**
70
71
```typescript
72
import { userEvent, page } from "@vitest/browser/context";
73
74
// Basic interactions
75
await userEvent.click(page.getByRole("button"));
76
await userEvent.type(page.getByLabelText("Username"), "john");
77
await userEvent.fill(page.getByPlaceholder("Email"), "john@example.com");
78
79
// Keyboard shortcuts
80
await userEvent.keyboard("{Ctrl}a"); // Select all
81
await userEvent.keyboard("{Ctrl}c"); // Copy
82
await userEvent.keyboard("{Ctrl}v"); // Paste
83
84
// File upload
85
const fileInput = page.getByLabelText("Upload file");
86
await userEvent.upload(fileInput, [
87
new File(["content"], "test.txt", { type: "text/plain" })
88
]);
89
90
// Create separate instance with its own state
91
const userEvent2 = userEvent.setup();
92
await userEvent2.type(input, "text");
93
await userEvent2.cleanup();
94
```
95
96
### Page Object
97
98
Browser page interface providing locator methods, viewport management, and screenshot capabilities.
99
100
```typescript { .api }
101
/**
102
* Browser page object with locator methods and screenshot capabilities
103
*/
104
const page: BrowserPage;
105
106
interface BrowserPage {
107
/** Change the size of iframe's viewport */
108
viewport(width: number, height: number): Promise<void>;
109
110
/** Make a screenshot of the test iframe or a specific element */
111
screenshot(options?: ScreenshotOptions): Promise<string>;
112
screenshot(options: Omit<ScreenshotOptions, 'base64'> & { base64: true }): Promise<{
113
path: string;
114
base64: string;
115
}>;
116
117
/** Extend default page object with custom methods */
118
extend(methods: Partial<BrowserPage>): BrowserPage;
119
120
/** Wrap an HTML element in a Locator */
121
elementLocator(element: Element): Locator;
122
123
// Locator selector methods
124
/** Creates a locator by ARIA role */
125
getByRole(role: string, options?: LocatorByRoleOptions): Locator;
126
/** Creates a locator by label text */
127
getByLabelText(text: string | RegExp, options?: LocatorOptions): Locator;
128
/** Creates a locator by alt text */
129
getByAltText(text: string | RegExp, options?: LocatorOptions): Locator;
130
/** Creates a locator by placeholder text */
131
getByPlaceholder(text: string | RegExp, options?: LocatorOptions): Locator;
132
/** Creates a locator by text content */
133
getByText(text: string | RegExp, options?: LocatorOptions): Locator;
134
/** Creates a locator by title attribute */
135
getByTitle(text: string | RegExp, options?: LocatorOptions): Locator;
136
/** Creates a locator by test ID attribute */
137
getByTestId(text: string | RegExp): Locator;
138
}
139
```
140
141
**Usage Examples:**
142
143
```typescript
144
import { page } from "@vitest/browser/context";
145
146
// Viewport management
147
await page.viewport(1024, 768);
148
149
// Screenshots
150
const imagePath = await page.screenshot({ path: "test-result.png" });
151
const { path, base64 } = await page.screenshot({ base64: true });
152
153
// Element location
154
const button = page.getByRole("button", { name: "Submit" });
155
const input = page.getByLabelText("Username");
156
const link = page.getByText("Click here");
157
158
// Extend with custom methods
159
const extendedPage = page.extend({
160
async loginUser(username: string, password: string) {
161
await userEvent.fill(this.getByLabelText("Username"), username);
162
await userEvent.fill(this.getByLabelText("Password"), password);
163
await userEvent.click(this.getByRole("button", { name: "Login" }));
164
}
165
});
166
```
167
168
### Commands Object
169
170
File system operations accessible from browser context for reading/writing files on the server.
171
172
```typescript { .api }
173
/**
174
* Available commands for the browser - server-side file operations
175
*/
176
const commands: BrowserCommands;
177
178
interface BrowserCommands {
179
/** Read file from server filesystem */
180
readFile(path: string, options?: BufferEncoding | FsOptions): Promise<string>;
181
/** Write file to server filesystem */
182
writeFile(path: string, content: string, options?: BufferEncoding | (FsOptions & { mode?: number | string })): Promise<void>;
183
/** Remove file from server filesystem */
184
removeFile(path: string): Promise<void>;
185
}
186
187
interface FsOptions {
188
encoding?: BufferEncoding;
189
flag?: string | number;
190
}
191
```
192
193
**Usage Examples:**
194
195
```typescript
196
import { commands } from "@vitest/browser/context";
197
198
// Read configuration files
199
const config = await commands.readFile("./config.json");
200
const parsed = JSON.parse(config);
201
202
// Write test outputs
203
await commands.writeFile("./output.json", JSON.stringify(testResults));
204
205
// Clean up test files
206
await commands.removeFile("./temp-test-file.txt");
207
208
// Read with specific encoding
209
const content = await commands.readFile("./data.txt", "utf8");
210
```
211
212
### Server Object
213
214
Information about the server environment and browser configuration.
215
216
```typescript { .api }
217
/**
218
* Server and browser metadata
219
*/
220
const server: ServerInfo;
221
222
interface ServerInfo {
223
/** Platform the Vitest server is running on (same as process.platform) */
224
platform: Platform;
225
/** Runtime version of the Vitest server (same as process.version) */
226
version: string;
227
/** Name of the browser provider (playwright, webdriverio, preview) */
228
provider: string;
229
/** Name of the current browser */
230
browser: string;
231
/** Available commands for the browser */
232
commands: BrowserCommands;
233
/** Serialized test config */
234
config: SerializedConfig;
235
}
236
237
type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
238
```
239
240
**Usage Examples:**
241
242
```typescript
243
import { server } from "@vitest/browser/context";
244
245
// Check browser environment
246
if (server.provider === "playwright") {
247
// Playwright-specific test logic
248
}
249
250
// Platform-specific behavior
251
if (server.platform === "win32") {
252
// Windows-specific paths
253
}
254
255
// Access browser info
256
console.log(`Running on ${server.browser} via ${server.provider}`);
257
258
// Access configuration
259
const testIdAttribute = server.config.browser.locators.testIdAttribute;
260
```
261
262
### Locators Object
263
264
Factory for creating locator selectors and extending locator functionality.
265
266
```typescript { .api }
267
/**
268
* Locator factory and extension methods
269
*/
270
const locators: BrowserLocators;
271
272
interface BrowserLocators {
273
/** Create element locator selectors for an existing element */
274
createElementLocators(element: Element): LocatorSelectors;
275
/** Extend locators with custom selector methods */
276
extend(methods: {
277
[K in keyof LocatorSelectors]?: (this: BrowserPage | Locator, ...args: Parameters<LocatorSelectors[K]>) => ReturnType<LocatorSelectors[K]> | string
278
}): void;
279
}
280
281
interface LocatorSelectors {
282
getByRole(role: string, options?: LocatorByRoleOptions): Locator;
283
getByLabelText(text: string | RegExp, options?: LocatorOptions): Locator;
284
getByAltText(text: string | RegExp, options?: LocatorOptions): Locator;
285
getByPlaceholder(text: string | RegExp, options?: LocatorOptions): Locator;
286
getByText(text: string | RegExp, options?: LocatorOptions): Locator;
287
getByTitle(text: string | RegExp, options?: LocatorOptions): Locator;
288
getByTestId(text: string | RegExp): Locator;
289
}
290
```
291
292
**Usage Examples:**
293
294
```typescript
295
import { locators, page } from "@vitest/browser/context";
296
297
// Create locator selectors for existing element
298
const existingElement = document.querySelector("#my-element");
299
const elementLocators = locators.createElementLocators(existingElement);
300
const childButton = elementLocators.getByRole("button");
301
302
// Extend with custom locator methods
303
locators.extend({
304
getByDataCy(this: BrowserPage | Locator, value: string) {
305
return this.locator(`[data-cy="${value}"]`);
306
}
307
});
308
309
// Now available on page and locators
310
const customElement = page.getByDataCy("submit-button");
311
```
312
313
### CDP Function
314
315
Chrome DevTools Protocol access for advanced browser automation (Playwright provider only).
316
317
```typescript { .api }
318
/**
319
* Chrome DevTools Protocol session access (Playwright provider only)
320
*/
321
const cdp: () => CDPSession;
322
323
interface CDPSession {
324
/** Send CDP command */
325
send<T extends keyof Protocol.CommandParameters>(
326
method: T,
327
params?: Protocol.CommandParameters[T]
328
): Promise<Protocol.CommandReturnValues[T]>;
329
330
/** Add event listener */
331
on<T extends keyof Protocol.Events>(
332
event: T,
333
listener: (payload: Protocol.Events[T]) => void
334
): this;
335
336
/** Add one-time event listener */
337
once<T extends keyof Protocol.Events>(
338
event: T,
339
listener: (payload: Protocol.Events[T]) => void
340
): this;
341
342
/** Remove event listener */
343
off<T extends keyof Protocol.Events>(
344
event: T,
345
listener: (payload: Protocol.Events[T]) => void
346
): this;
347
}
348
```
349
350
**Usage Examples:**
351
352
```typescript
353
import { cdp } from "@vitest/browser/context";
354
355
// Get CDP session (Playwright only)
356
const session = cdp();
357
358
// Enable runtime domain
359
await session.send('Runtime.enable');
360
361
// Listen to console events
362
session.on('Runtime.consoleAPICalled', (event) => {
363
console.log('Browser console:', event.args);
364
});
365
366
// Evaluate JavaScript
367
const result = await session.send('Runtime.evaluate', {
368
expression: 'document.title'
369
});
370
```
371
372
## Types
373
374
Option interfaces for user events and locators:
375
376
```typescript { .api }
377
interface UserEventClickOptions {}
378
interface UserEventDoubleClickOptions {}
379
interface UserEventTripleClickOptions {}
380
interface UserEventFillOptions {}
381
interface UserEventClearOptions {}
382
interface UserEventHoverOptions {}
383
interface UserEventSelectOptions {}
384
interface UserEventUploadOptions {}
385
interface UserEventDragAndDropOptions {}
386
387
interface UserEventTabOptions {
388
shift?: boolean;
389
}
390
391
interface UserEventTypeOptions {
392
skipClick?: boolean;
393
skipAutoClose?: boolean;
394
}
395
```