网络与模拟
🌐 Network & Mocking
检查网络流量,模拟 API 响应,并测试离线行为。
🌐 Inspect network traffic, mock API responses, and test offline behavior.
检查网络请求
🌐 Inspect network requests
playwright-cli network # all requests since page load
playwright-cli network --filter="api" # filter by URL pattern
playwright-cli network --static # include images, CSS, fonts
playwright-cli network --request-body # include request bodies
playwright-cli network --request-headers # include headers
playwright-cli network --clear # clear the log
$ playwright-cli network --filter="api"
# GET 200 https://api.example.com/users 12ms application/json
# POST 201 https://api.example.com/users/create 45ms application/json
模拟 API 响应
🌐 Mock API responses
playwright-cli route <pattern> [options]
| 选项 | 描述 |
|---|---|
--status=<code> | HTTP 状态码 |
--body=<text> | 响应体(文本或 JSON 字符串) |
--content-type=<type> | Content-Type 头 |
--header=<name:value> | 额外响应头 |
--remove-header=<names> | 从请求中移除的头(逗号分隔) |
模拟一个 API 端点
🌐 Mock an API endpoint
playwright-cli route "**/api/users" \
--body='[{"name":"Alice"},{"name":"Bob"}]' \
--content-type=application/json
测试错误处理
🌐 Test error handling
playwright-cli route "**/api/data" --status=500
playwright-cli route "**/api/data" --status=503
阻止资源
🌐 Block resources
playwright-cli route "**/*.jpg" --status=404
playwright-cli route "**/analytics/**" --status=204
移除认证头
🌐 Strip authentication headers
playwright-cli route "**/*" --remove-header=cookie,authorization
管理路由
🌐 Manage routes
playwright-cli route-list # list active routes
playwright-cli unroute "**/api/users" # remove specific route
playwright-cli unroute # remove all routes
带条件的代码模拟
🌐 Conditional mocking with code
对于复杂场景——延迟、条件响应或请求体检查——使用 run-code:
🌐 For complex scenarios -- delays, conditional responses, or request body inspection -- use run-code:
playwright-cli run-code "async (page) => {
await page.route('**/api/users', async route => {
const body = route.request().postDataJSON();
if (body.role === 'admin') {
await route.fulfill({
body: JSON.stringify({ permissions: ['read', 'write', 'delete'] })
});
} else {
await route.fulfill({
body: JSON.stringify({ permissions: ['read'] })
});
}
});
}"
工作流程:测试错误处理
🌐 Workflow: testing error handling
# 1. Mock the API to return 503
playwright-cli route "**/api/users" --status=503
# 2. Reload to trigger the error
playwright-cli reload
# 3. Verify the error page
playwright-cli snapshot
# - heading "Something went wrong" [level=1]
# - button "Retry" [ref=e5]
# 4. Screenshot the error state
playwright-cli screenshot --filename=error-state.png
# 5. Remove mock and retry
playwright-cli unroute
playwright-cli click e5
playwright-cli snapshot
# - heading "Users" [level=1]
测试离线模式
🌐 Test offline mode
playwright-cli network-state-set offline # go offline
playwright-cli reload # page shows offline state
playwright-cli snapshot
# - heading "No internet connection" [level=1]
playwright-cli network-state-set online # restore connection
playwright-cli reload # page loads normally