Skip to content

Commit 7c330b5

Browse files
committed
Create request-mocking.md
1 parent 1ffa387 commit 7c330b5

1 file changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
# Request Mocking
2+
3+
Intercept, mock, modify, and block network requests.
4+
5+
## CLI Route Commands
6+
7+
```bash
8+
# Mock with custom status
9+
playwright-cli route "**/*.jpg" --status=404
10+
11+
# Mock with JSON body
12+
playwright-cli route "**/api/users" --body='[{"id":1,"name":"Alice"}]' --content-type=application/json
13+
14+
# Mock with custom headers
15+
playwright-cli route "**/api/data" --body='{"ok":true}' --header="X-Custom: value"
16+
17+
# Remove headers from requests
18+
playwright-cli route "**/*" --remove-header=cookie,authorization
19+
20+
# List active routes
21+
playwright-cli route-list
22+
23+
# Remove a route or all routes
24+
playwright-cli unroute "**/*.jpg"
25+
playwright-cli unroute
26+
```
27+
28+
## URL Patterns
29+
30+
```
31+
**/api/users - Exact path match
32+
**/api/*/details - Wildcard in path
33+
**/*.{png,jpg,jpeg} - Match file extensions
34+
**/search?q=* - Match query parameters
35+
```
36+
37+
## Advanced Mocking with run-code
38+
39+
For conditional responses, request body inspection, response modification, or delays:
40+
41+
### Conditional Response Based on Request
42+
43+
```bash
44+
playwright-cli run-code "async page => {
45+
await page.route('**/api/login', route => {
46+
const body = route.request().postDataJSON();
47+
if (body.username === 'admin') {
48+
route.fulfill({ body: JSON.stringify({ token: 'mock-token' }) });
49+
} else {
50+
route.fulfill({ status: 401, body: JSON.stringify({ error: 'Invalid' }) });
51+
}
52+
});
53+
}"
54+
```
55+
56+
### Modify Real Response
57+
58+
```bash
59+
playwright-cli run-code "async page => {
60+
await page.route('**/api/user', async route => {
61+
const response = await route.fetch();
62+
const json = await response.json();
63+
json.isPremium = true;
64+
await route.fulfill({ response, json });
65+
});
66+
}"
67+
```
68+
69+
### Simulate Network Failures
70+
71+
```bash
72+
playwright-cli run-code "async page => {
73+
await page.route('**/api/offline', route => route.abort('internetdisconnected'));
74+
}"
75+
# Options: connectionrefused, timedout, connectionreset, internetdisconnected
76+
```
77+
78+
### Delayed Response
79+
80+
```bash
81+
playwright-cli run-code "async page => {
82+
await page.route('**/api/slow', async route => {
83+
await new Promise(r => setTimeout(r, 3000));
84+
route.fulfill({ body: JSON.stringify({ data: 'loaded' }) });
85+
});
86+
}"
87+
```

0 commit comments

Comments
 (0)