0
# Testing Utilities
1
2
Built-in testing, debugging, and performance utilities including network mocking, CPU/network throttling, interactive debugging, and browser integration tools.
3
4
## Capabilities
5
6
### Network Mocking
7
8
Mock network requests and responses for testing scenarios.
9
10
```typescript { .api }
11
/**
12
* Create a network mock for intercepting requests
13
* @param url - URL pattern to mock (string or RegExp)
14
* @param options - Mock configuration options
15
* @returns Promise resolving to a Mock instance
16
*/
17
mock(url: string, options?: object): Promise<WebdriverIO.Mock>;
18
19
/**
20
* Restore all network mocks to their original state
21
* @returns Promise that resolves when all mocks are restored
22
*/
23
mockRestoreAll(): Promise<void>;
24
25
/**
26
* Clear all network mock call history and state
27
* @returns Promise that resolves when all mocks are cleared
28
*/
29
mockClearAll(): Promise<void>;
30
31
interface WebdriverIO.Mock {
32
calls: MockCall[];
33
restore(): void;
34
clear(): void;
35
respond(response: MockResponse): void;
36
respondOnce(response: MockResponse): void;
37
abort(errorCode?: string): void;
38
abortOnce(errorCode?: string): void;
39
}
40
41
interface MockCall {
42
url: string;
43
method: string;
44
headers: object;
45
body: string;
46
timestamp: number;
47
}
48
49
interface MockResponse {
50
statusCode?: number;
51
headers?: object;
52
body?: string | object;
53
delay?: number;
54
}
55
```
56
57
**Usage Examples:**
58
59
```typescript
60
// Mock API endpoint
61
const apiMock = await browser.mock('**/api/users');
62
apiMock.respond({
63
statusCode: 200,
64
body: {
65
users: [
66
{ id: 1, name: 'John Doe' },
67
{ id: 2, name: 'Jane Smith' }
68
]
69
}
70
});
71
72
// Mock with delay
73
const slowApiMock = await browser.mock('**/api/slow-endpoint');
74
slowApiMock.respond({
75
statusCode: 200,
76
body: { message: 'Success' },
77
delay: 3000
78
});
79
80
// Mock error responses
81
const errorMock = await browser.mock('**/api/error');
82
errorMock.respond({
83
statusCode: 500,
84
body: { error: 'Internal Server Error' }
85
});
86
87
// Inspect mock calls
88
await browser.url('/test-page');
89
console.log(apiMock.calls.length); // Number of intercepted calls
90
console.log(apiMock.calls[0].body); // Request body of first call
91
92
// Clean up mocks
93
await browser.mockRestoreAll();
94
```
95
96
### Performance Testing
97
98
Tools for simulating various performance conditions and constraints.
99
100
```typescript { .api }
101
/**
102
* Throttle CPU performance
103
* @param rate - CPU throttling rate (1 = no throttling, 4 = 4x slower)
104
* @returns Promise that resolves when throttling is applied
105
*/
106
throttleCPU(rate: number): Promise<void>;
107
108
/**
109
* Apply network throttling conditions
110
* @param conditions - Network throttling configuration
111
* @returns Promise that resolves when throttling is applied
112
*/
113
throttleNetwork(conditions: object): Promise<void>;
114
115
/**
116
* Apply general throttling conditions (legacy method)
117
* @param condition - Throttling condition name or configuration
118
* @returns Promise that resolves when throttling is applied
119
*/
120
throttle(condition: string): Promise<void>;
121
```
122
123
**Usage Examples:**
124
125
```typescript
126
// Throttle CPU to simulate slower devices
127
await browser.throttleCPU(4); // 4x slower CPU
128
129
// Apply network throttling for 3G simulation
130
await browser.throttleNetwork({
131
offline: false,
132
downloadThroughput: 1.5 * 1024 * 1024 / 8, // 1.5 Mbps
133
uploadThroughput: 750 * 1024 / 8, // 750 Kbps
134
latency: 150 // 150ms latency
135
});
136
137
// Use predefined throttling profiles
138
await browser.throttle('Regular 3G');
139
await browser.throttle('Good 3G');
140
await browser.throttle('Slow 3G');
141
142
// Disable throttling
143
await browser.throttleNetwork({ offline: false });
144
await browser.throttleCPU(1);
145
```
146
147
### Debugging and Development
148
149
Interactive debugging and development assistance tools.
150
151
```typescript { .api }
152
/**
153
* Start an interactive debugging session with REPL
154
* @returns Promise that resolves when debugging session ends
155
*/
156
debug(): Promise<void>;
157
158
/**
159
* Pause execution for a specified duration
160
* @param milliseconds - Duration to pause in milliseconds
161
* @returns Promise that resolves after the pause
162
*/
163
pause(milliseconds: number): Promise<void>;
164
165
/**
166
* Add an initialization script that runs before page load
167
* @param script - JavaScript function or string to execute
168
* @returns Promise resolving to InitScript object
169
*/
170
addInitScript(script: Function | string): Promise<InitScript>;
171
172
interface InitScript {
173
id: string;
174
source: string;
175
}
176
```
177
178
**Usage Examples:**
179
180
```typescript
181
// Start interactive debugging
182
await browser.url('https://example.com');
183
await browser.debug(); // Opens REPL for interactive testing
184
185
// Add strategic pauses for observation
186
await browser.pause(2000); // Wait 2 seconds
187
188
// Add initialization script
189
await browser.addInitScript(() => {
190
// This runs before each page load
191
window.testMode = true;
192
console.log('Test mode enabled');
193
});
194
195
// Add initialization script as string
196
await browser.addInitScript(`
197
window.customTracker = {
198
events: [],
199
track: function(event) {
200
this.events.push({ event: event, timestamp: Date.now() });
201
}
202
};
203
`);
204
```
205
206
### Browser Integration
207
208
Tools for integrating with browser-specific features and debugging tools.
209
210
```typescript { .api }
211
/**
212
* Get access to the underlying Puppeteer browser instance (Chrome/Edge only)
213
* @returns Promise resolving to Puppeteer browser instance
214
*/
215
getPuppeteer(): Promise<PuppeteerBrowser>;
216
217
/**
218
* Emulate a specific device with predefined characteristics
219
* @param device - Device configuration object
220
* @returns Promise that resolves when device emulation is applied
221
*/
222
emulate(device: object): Promise<void>;
223
```
224
225
**Usage Examples:**
226
227
```typescript
228
// Access Puppeteer for advanced Chrome features
229
const puppeteerBrowser = await browser.getPuppeteer();
230
const pages = await puppeteerBrowser.pages();
231
const page = pages[0];
232
233
// Use Puppeteer API directly
234
await page.coverage.startJSCoverage();
235
await browser.url('https://example.com');
236
const coverage = await page.coverage.stopJSCoverage();
237
238
// Emulate mobile device
239
await browser.emulate({
240
name: 'iPhone 12',
241
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15',
242
viewport: {
243
width: 390,
244
height: 844,
245
deviceScaleFactor: 3,
246
isMobile: true,
247
hasTouch: true
248
}
249
});
250
251
// Emulate desktop device
252
await browser.emulate({
253
name: 'Desktop',
254
viewport: {
255
width: 1920,
256
height: 1080,
257
deviceScaleFactor: 1,
258
isMobile: false,
259
hasTouch: false
260
}
261
});
262
```
263
264
### Wait Utilities
265
266
Advanced waiting and synchronization utilities for robust test execution.
267
268
```typescript { .api }
269
/**
270
* Wait until a custom condition is met
271
* @param condition - Function that returns true when condition is satisfied
272
* @param options - Wait configuration options
273
* @returns Promise resolving to the condition function's return value
274
*/
275
waitUntil(condition: Function, options?: object): Promise<any>;
276
277
interface WaitOptions {
278
timeout?: number;
279
timeoutMsg?: string;
280
interval?: number;
281
}
282
```
283
284
**Usage Examples:**
285
286
```typescript
287
// Wait for element to appear
288
await browser.waitUntil(async () => {
289
const element = await browser.$('#dynamic-element');
290
return await element.isExisting();
291
}, {
292
timeout: 10000,
293
timeoutMsg: 'Dynamic element never appeared'
294
});
295
296
// Wait for API data to load
297
await browser.waitUntil(async () => {
298
const result = await browser.execute(() => {
299
return window.apiDataLoaded === true;
300
});
301
return result;
302
}, {
303
timeout: 15000,
304
interval: 500
305
});
306
307
// Wait for complex condition
308
await browser.waitUntil(async () => {
309
const elements = await browser.$$('.list-item');
310
return elements.length >= 5;
311
}, {
312
timeout: 20000,
313
timeoutMsg: 'Expected at least 5 list items to be present'
314
});
315
```
316
317
### Test Automation Helpers
318
319
Utility functions specifically designed for test automation workflows.
320
321
```typescript { .api }
322
/**
323
* Set timeout values for various WebDriver operations
324
* @param timeouts - Timeout configuration object
325
* @returns Promise that resolves when timeouts are configured
326
*/
327
setTimeout(timeouts: object): Promise<void>;
328
329
/**
330
* Call a function with the browser instance as context
331
* @param callback - Function to execute with browser context
332
* @returns Promise resolving to the callback's return value
333
*/
334
call(callback: Function): Promise<any>;
335
```
336
337
**Usage Examples:**
338
339
```typescript
340
// Configure various timeouts
341
await browser.setTimeout({
342
implicit: 5000, // Element finding timeout
343
pageLoad: 30000, // Page load timeout
344
script: 15000 // JavaScript execution timeout
345
});
346
347
// Execute complex test logic with browser context
348
const testResults = await browser.call(async function() {
349
// 'this' refers to the browser instance
350
await this.url('https://example.com/form');
351
352
const form = await this.$('#contact-form');
353
await form.$('#name').setValue('Test User');
354
await form.$('#email').setValue('test@example.com');
355
await form.$('#submit').click();
356
357
const success = await this.$('.success-message');
358
const isVisible = await success.waitForDisplayed({ timeout: 5000 });
359
360
return {
361
formSubmitted: true,
362
successVisible: isVisible,
363
currentUrl: await this.getUrl()
364
};
365
});
366
367
console.log(testResults);
368
```
369
370
### Environment Detection
371
372
Utilities for detecting and adapting to different execution environments.
373
374
```typescript { .api }
375
// Environment detection utilities (typically used internally)
376
interface EnvironmentInfo {
377
isNode: boolean;
378
isBrowser: boolean;
379
platform: string;
380
capabilities: object;
381
}
382
```
383
384
These utilities help WebdriverIO adapt its behavior based on whether it's running in Node.js or browser environments, and what capabilities are available in the current WebDriver session.