0
# Server Integration
1
2
Node.js server-side functionality for creating browser test environments and managing browser pools in test suites, providing the infrastructure for running browser tests.
3
4
## Capabilities
5
6
### Browser Server Creation
7
8
Create and configure browser test servers for Vitest test execution.
9
10
```typescript { .api }
11
/**
12
* Creates a browser server instance for running tests
13
* @param project - Vitest test project instance
14
* @param configFile - Optional path to Vite config file
15
* @param prePlugins - Plugins to add before default plugins
16
* @param postPlugins - Plugins to add after default plugins
17
* @returns Promise resolving to ParentBrowserProject instance
18
*/
19
function createBrowserServer(
20
project: TestProject,
21
configFile: string | undefined,
22
prePlugins?: Plugin[],
23
postPlugins?: Plugin[]
24
): Promise<ParentBrowserProject>;
25
```
26
27
**Usage Examples:**
28
29
```typescript
30
import { createBrowserServer } from "@vitest/browser";
31
import type { TestProject, Plugin } from "vitest/node";
32
33
// Basic browser server creation
34
async function setupBrowserTests(project: TestProject) {
35
const browserServer = await createBrowserServer(
36
project,
37
undefined // Use default config
38
);
39
40
return browserServer;
41
}
42
43
// With custom plugins
44
const customPlugin: Plugin = {
45
name: 'custom-plugin',
46
configureServer(server) {
47
// Custom server configuration
48
}
49
};
50
51
const browserServer = await createBrowserServer(
52
project,
53
'./vitest.config.ts',
54
[customPlugin], // Pre-plugins
55
[] // Post-plugins
56
);
57
```
58
59
### Browser Pool Management
60
61
Create and manage pools of browser instances for parallel test execution.
62
63
```typescript { .api }
64
/**
65
* Creates a browser test pool for managing multiple browser instances
66
* @param vitest - Vitest instance for test execution
67
* @returns ProcessPool instance for parallel test execution
68
*/
69
function createBrowserPool(vitest: Vitest): ProcessPool;
70
```
71
72
**Usage Examples:**
73
74
```typescript
75
import { createBrowserPool } from "@vitest/browser";
76
import type { Vitest } from "vitest/node";
77
78
// Create browser pool for parallel testing
79
function setupBrowserPool(vitest: Vitest) {
80
const browserPool = createBrowserPool(vitest);
81
return browserPool;
82
}
83
84
// Pool is typically managed internally by Vitest
85
// but can be used for custom test orchestration
86
```
87
88
### Project Browser Interface
89
90
Interface for browser-specific project configuration and management.
91
92
```typescript { .api }
93
/**
94
* Browser project interface for configuration and test management
95
*/
96
interface ProjectBrowser {
97
// Project browser implementation details
98
// (specific properties depend on internal implementation)
99
}
100
```
101
102
### Distribution Root
103
104
Path constant for accessing browser package distribution files.
105
106
```typescript { .api }
107
/**
108
* Path to the distribution directory of @vitest/browser package
109
*/
110
const distRoot: string;
111
```
112
113
**Usage Examples:**
114
115
```typescript
116
import { distRoot } from "@vitest/browser";
117
import { join } from "path";
118
119
// Access client-side assets
120
const clientScriptPath = join(distRoot, "client.js");
121
const locatorScriptPath = join(distRoot, "locators", "index.js");
122
123
// Useful for custom plugin development
124
function customBrowserPlugin() {
125
return {
126
name: 'custom-browser-plugin',
127
configureServer(server) {
128
// Serve additional browser assets
129
server.middlewares.use('/browser-assets', express.static(distRoot));
130
}
131
};
132
}
133
```
134
135
### Server Configuration
136
137
The browser server handles several key responsibilities:
138
139
**Vite Server Integration:**
140
- Creates optimized Vite development server for browser tests
141
- Handles module resolution and hot reloading
142
- Manages client-server communication
143
144
**Provider Integration:**
145
- Sets up browser automation providers (Playwright, WebdriverIO, Preview)
146
- Configures browser-specific settings and capabilities
147
- Manages browser lifecycle and cleanup
148
149
**Mocker Registry:**
150
- Integrates with @vitest/mocker for module mocking
151
- Handles browser-side mock registration and cleanup
152
- Provides mock synchronization between server and client
153
154
**Plugin System:**
155
- Supports custom Vite plugins for browser testing
156
- Provides hooks for test lifecycle management
157
- Enables extension of browser testing capabilities
158
159
### Advanced Server Usage
160
161
**Custom Plugin Development:**
162
163
```typescript
164
import { createBrowserServer } from "@vitest/browser";
165
import type { Plugin } from "vite";
166
167
// Custom plugin for browser tests
168
const browserTestPlugin: Plugin = {
169
name: 'browser-test-plugin',
170
configureServer(server) {
171
// Add custom middleware
172
server.middlewares.use('/api', (req, res, next) => {
173
// Handle test API requests
174
if (req.url?.startsWith('/api/test-data')) {
175
res.setHeader('Content-Type', 'application/json');
176
res.end(JSON.stringify({ data: 'test' }));
177
} else {
178
next();
179
}
180
});
181
},
182
buildStart() {
183
// Setup test environment
184
console.log('Browser test environment starting...');
185
}
186
};
187
188
// Use plugin with browser server
189
const browserServer = await createBrowserServer(
190
project,
191
configFile,
192
[browserTestPlugin]
193
);
194
```
195
196
**Environment Configuration:**
197
198
```typescript
199
// vitest.config.ts - Server-side configuration
200
export default defineConfig({
201
test: {
202
browser: {
203
enabled: true,
204
provider: 'playwright',
205
name: 'chromium',
206
// Server-side options
207
providerOptions: {
208
launch: {
209
headless: process.env.CI === 'true',
210
devtools: !process.env.CI
211
}
212
}
213
}
214
},
215
server: {
216
// Vite server options for browser tests
217
port: 3000,
218
host: true,
219
fs: {
220
// Allow serving files from test fixtures
221
allow: ['..']
222
}
223
}
224
});
225
```
226
227
**Test Project Integration:**
228
229
```typescript
230
import { createBrowserServer } from "@vitest/browser";
231
import type { TestProject } from "vitest/node";
232
233
class CustomTestRunner {
234
private browserServer?: ParentBrowserProject;
235
236
async setup(project: TestProject) {
237
// Create browser server with project configuration
238
this.browserServer = await createBrowserServer(project, project.config.configFile);
239
240
// Server is now ready for browser tests
241
console.log(`Browser server ready on port ${this.browserServer.port}`);
242
}
243
244
async runTests() {
245
if (!this.browserServer) {
246
throw new Error('Browser server not initialized');
247
}
248
249
// Run tests using the browser server
250
// (typically handled by Vitest internally)
251
}
252
253
async cleanup() {
254
if (this.browserServer) {
255
await this.browserServer.close();
256
}
257
}
258
}
259
```
260
261
### Error Handling
262
263
Common server-side error scenarios and handling:
264
265
```typescript
266
import { createBrowserServer } from "@vitest/browser";
267
268
try {
269
const browserServer = await createBrowserServer(project, configFile);
270
} catch (error) {
271
if (error.message.includes('version mismatch')) {
272
console.error('Vitest and @vitest/browser versions do not match');
273
// Handle version compatibility issues
274
} else if (error.message.includes('port already in use')) {
275
console.error('Server port is already in use');
276
// Handle port conflicts
277
} else {
278
console.error('Failed to create browser server:', error);
279
// Handle other server creation errors
280
}
281
}
282
```
283
284
### Integration with Vitest
285
286
The server API is typically used internally by Vitest, but understanding it helps with:
287
288
**Custom Test Environments:**
289
```typescript
290
// Custom environment that uses browser server
291
export default class BrowserTestEnvironment implements Environment {
292
private browserServer?: ParentBrowserProject;
293
294
async setup(project: TestProject) {
295
this.browserServer = await createBrowserServer(project);
296
// Environment is ready
297
}
298
}
299
```
300
301
**Plugin Development:**
302
```typescript
303
// Vitest plugin that enhances browser testing
304
function vitestBrowserPlugin(): Plugin {
305
return {
306
name: 'vitest-browser-plugin',
307
config(config) {
308
// Modify browser test configuration
309
if (config.test?.browser?.enabled) {
310
// Add browser-specific settings
311
}
312
}
313
};
314
}
315
```
316
317
## Types
318
319
Server-side type definitions:
320
321
```typescript { .api }
322
interface ParentBrowserProject {
323
// Internal browser project implementation
324
// Handles browser test orchestration and lifecycle
325
}
326
327
interface BrowserPool {
328
// Internal browser pool implementation
329
// Manages multiple browser instances for parallel testing
330
}
331
```