0
# Client API
1
2
The Client API provides browser-based functionality for interacting with Vitest through WebSocket connections, enabling real-time test execution, file management, and result viewing. These APIs are available in the browser context when the @vitest/ui interface is loaded.
3
4
## Browser Context Access
5
6
The client APIs are available in the browser when the Vitest UI is running. They are not importable from the npm package but are accessible through the UI framework's module system. The UI API is exposed as a global object:
7
8
```typescript
9
// UI API available as global in browser context
10
const ui = window.__vitest_ui_api__;
11
12
// Client is available through the UI framework's composables
13
// (actual access varies based on the UI framework implementation)
14
```
15
16
## API
17
18
### Client Instance
19
20
The main WebSocket client for communicating with Vitest.
21
22
```typescript { .api }
23
declare const client: {
24
state: {
25
idMap: Map<string, Task>;
26
filesMap: Map<string, File[]>;
27
pathsSet: Set<string>;
28
getPaths(): string[];
29
getFiles(keys?: string[]): File[];
30
getFilepaths(): string[];
31
getFailedFilepaths(): string[];
32
collectPaths(paths: string[]): void;
33
collectFiles(files: File[]): void;
34
};
35
rpc: {
36
rerun(files: string[], allTests: boolean): Promise<void>;
37
rerunTask(taskId: string): Promise<void>;
38
getFiles(): Promise<File[]>;
39
getConfig(): Promise<SerializedConfig>;
40
getUnhandledErrors(): Promise<unknown[]>;
41
getResolvedProjectLabels(): Promise<string[]>;
42
getTestFiles(): Promise<Array<[{ name: string; root: string }, string]>>;
43
readTestFile(filepath: string): Promise<string>;
44
saveTestFile(filepath: string, content: string): Promise<void>;
45
updateSnapshot(file: File): Promise<void>;
46
};
47
ws: WebSocket;
48
};
49
```
50
51
### Configuration and State
52
53
Reactive state objects for monitoring Vitest configuration and connection status.
54
55
```typescript { .api }
56
declare const config: Ref<SerializedConfig>;
57
declare const status: Ref<WebSocketStatus>;
58
declare const current: ComputedRef<File | undefined>;
59
declare const currentLogs: ComputedRef<TaskLog[]>;
60
```
61
62
### Connection State Helpers
63
64
Computed properties for checking WebSocket connection status.
65
66
```typescript { .api }
67
declare const isConnected: ComputedRef<boolean>;
68
declare const isConnecting: ComputedRef<boolean>;
69
declare const isDisconnected: ComputedRef<boolean>;
70
```
71
72
### Test Execution Functions
73
74
Functions for running tests and managing test execution.
75
76
```typescript { .api }
77
declare function findById(id: string): File | undefined;
78
declare function runAll(): Promise<void>;
79
declare function runFiles(useFiles: File[]): Promise<void>;
80
declare function runTask(task: Task): Promise<void>;
81
declare function runCurrent(): Promise<void>;
82
```
83
84
### Browser UI Interface
85
86
Interface exposed to browser contexts for programmatic control.
87
88
```typescript { .api }
89
interface BrowserUI {
90
setCurrentFileId(fileId: string): void;
91
setIframeViewport(width: number, height: number): Promise<void>;
92
}
93
94
declare const ui: BrowserUI;
95
```
96
97
## Usage Examples
98
99
### Running Tests
100
101
```typescript
102
// Available in browser context when UI is loaded
103
// Note: client access depends on the UI framework implementation
104
// These examples show the expected API structure
105
106
// Run all tests
107
await runAll();
108
109
// Run specific files
110
const files = client.state.getFiles().filter(f => f.name.includes('auth'));
111
await runFiles(files);
112
113
// Run a specific task
114
const task = findById('test-task-id');
115
if (task) {
116
await runTask(task);
117
}
118
```
119
120
### Monitoring Connection Status
121
122
```typescript
123
// Available in browser context through UI framework composables
124
// Note: actual access may vary based on implementation
125
126
// Watch connection status
127
watch(status, (newStatus) => {
128
console.log('WebSocket status:', newStatus);
129
});
130
131
// Check connection state
132
if (isConnected.value) {
133
console.log('Connected to Vitest');
134
} else if (isConnecting.value) {
135
console.log('Connecting to Vitest...');
136
}
137
```
138
139
### Working with Test Files
140
141
```typescript
142
// Available in browser context through UI framework composables
143
// Note: actual access may vary based on implementation
144
145
// Get all test files
146
const allFiles = client.state.getFiles();
147
148
// Get current active file
149
const activeFile = current.value;
150
151
// Find file by ID
152
const specificFile = findById('file-123');
153
154
// Read test file content
155
const fileContent = await client.rpc.readTestFile('/path/to/test.spec.ts');
156
157
// Save modified test file
158
await client.rpc.saveTestFile('/path/to/test.spec.ts', updatedContent);
159
160
// Update snapshots for a file
161
await client.rpc.updateSnapshot(testFile);
162
```
163
164
### Browser Integration
165
166
```typescript
167
// The UI API is automatically exposed to the browser context
168
window.__vitest_ui_api__.setCurrentFileId('test-file-id');
169
window.__vitest_ui_api__.setIframeViewport(1920, 1080);
170
```
171
172
## WebSocket Events
173
174
The client handles several WebSocket events:
175
176
- `onTestAnnotate`: Handles test annotations and metadata
177
- `onTaskUpdate`: Processes test result updates in real-time
178
- `onFinished`: Handles test run completion
179
- `onFinishedReportCoverage`: Triggers coverage report reload
180
181
## Constants
182
183
```typescript { .api }
184
declare const PORT: string;
185
declare const HOST: string;
186
declare const ENTRY_URL: string;
187
declare const isReport: boolean;
188
declare const BASE_PATH: string;
189
```
190
191
## Explorer Tree Integration
192
193
The client integrates with the Explorer Tree for test result visualization:
194
195
```typescript { .api }
196
declare const explorerTree: {
197
loadFiles(files: File[], projects: string[]): void;
198
startRun(): void;
199
endRun(): void;
200
resumeRun(packs: TaskResultPack[], events: RunnerTaskEventPack[]): void;
201
annotateTest(testId: string, annotation: TestAnnotation): void;
202
};
203
```
204
205
## Types
206
207
```typescript { .api }
208
type WebSocketStatus = 'CONNECTING' | 'OPEN' | 'CLOSED';
209
210
interface File {
211
id: string;
212
name: string;
213
filepath: string;
214
projectName?: string;
215
result?: TaskResult;
216
mode: 'run' | 'skip' | 'only' | 'todo';
217
}
218
219
interface Task {
220
id: string;
221
name: string;
222
type: 'test' | 'suite';
223
mode: 'run' | 'skip' | 'only' | 'todo';
224
result?: TaskResult;
225
tasks?: Task[];
226
}
227
228
interface TaskLog {
229
type: 'stdout' | 'stderr';
230
content: string;
231
time: number;
232
}
233
234
interface TaskResult {
235
state?: 'pass' | 'fail' | 'skip' | 'todo';
236
duration?: number;
237
error?: unknown;
238
}
239
240
interface TaskResultPack {
241
id: string;
242
result: TaskResult;
243
}
244
245
interface RunnerTaskEventPack {
246
type: string;
247
taskId: string;
248
data: unknown;
249
}
250
251
interface TestAnnotation {
252
type: string;
253
message?: string;
254
attachment?: TestAttachment;
255
}
256
257
interface TestAttachment {
258
path?: string;
259
body?: string | Buffer;
260
contentType?: string;
261
}
262
263
// External types from dependencies:
264
// - Ref, ComputedRef: from Vue.js or compatible reactivity system
265
// - SerializedConfig: from 'vitest'
266
```