Skip to main content

网络与模拟

🌐 Network & Mocking

检查网络流量,模拟 API 响应,并测试离线行为。

🌐 Inspect network traffic, mock API responses, and test offline behavior.

检查网络请求

🌐 Inspect network requests

requests 会打印自页面加载以来所发出的请求的编号列表。默认情况下,成功的静态资源(图片、字体、样式表、脚本)是隐藏的,以保持列表简洁。

playwright-cli requests # fetch/XHR and anything that failed
playwright-cli requests --static # include successful static resources
playwright-cli requests --filter="/api/.*" # only URLs matching this regexp
playwright-cli requests --clear # clear the log
$ playwright-cli requests --filter="/api/"
# 1. [GET] https://api.example.com/users => [200] OK
# 2. [POST] https://api.example.com/users/create => [201] Created
# 3. [GET] https://api.example.com/prefs => [FAILED] net::ERR_ABORTED
#
# Note: 14 static requests not shown, run with --static option to see them.

检查一个请求

🌐 Inspect a single request

使用 requests 的号码:

🌐 Use the number from requests:

命令描述
request <index>完整详情 — 请求头和请求体,响应头和响应体
request-headers <index>仅请求头
request-body <index>仅请求体
response-headers <index>仅响应头
response-body <index>仅响应体
playwright-cli request 2
playwright-cli response-body 2
playwright-cli response-body 2 --filename=users.json

所有五个都接受 --filename 来把结果写入文件,而不是以文本形式返回。response-body 会把文本内容内联,而把二进制内容保存到文件,并打印路径。

🌐 All five accept --filename to write the result to a file instead of returning it as text. response-body inlines textual bodies and saves binary ones to a file, printing the path.

模拟 API 响应

🌐 Mock API responses

playwright-cli route <pattern> [options]
选项描述
--status=<code>HTTP 状态码(默认:200)
--body=<text>响应体(文本或 JSON 字符串)
--content-type=<type>模拟响应的 Content-Type 头
--header="<name>: <value>"添加到发出请求的头(可重复)
--remove-header=<names>用逗号分隔的请求中要移除的头名字

一个路由要么 完成,要么 重写。传入 --body--status 会用模拟响应完成请求,页面根本不会访问网络。只传 --header / --remove-header 会让请求带着修改过的头信息继续发送到真实服务器。

🌐 A route either fulfills or rewrites. Passing --body or --status fulfills the request with a mock response and the page never reaches the network. Passing only --header / --remove-header lets the request continue to the real server with modified headers.

模拟一个 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

重写请求头

🌐 Rewrite request headers

# strip credentials from every request
playwright-cli route "**/*" --remove-header=cookie,authorization

# add a header to API calls
playwright-cli route "**/api/**" --header="X-Debug: 1"

管理路由

🌐 Manage routes

playwright-cli route-list # list active routes
playwright-cli unroute "**/api/users" # remove specific route
playwright-cli unroute # remove all routes

URL 模式

🌐 URL patterns

**/api/users - match this path on any origin
**/api/*/details - wildcard segment
**/*.{png,jpg,jpeg} - match file extensions
**/search?q=* - match query parameters

带条件的代码模拟

🌐 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