快速开始
用 AI agent 搭建(推荐)
Section titled “用 AI agent 搭建(推荐)”把下面这段复制粘贴给你的 AI 编码 agent(Claude Code、Cursor、……):
Set up test-proxy-recorder for end-to-end tests in this project, then follow theinstructions that `init` prints. Run these commands:
npm install --save-dev test-proxy-recorder npx @tanstack/intent@latest install
Then run init, passing this project's backend API base URL as the target — findit yourself from the app's env/config (the URL the app calls in dev); don'tassume the default:
npx test-proxy-recorder init <your-backend-api-url> --port 8100 --dir ./e2e/recordings
Then complete the app-specific steps init prints: point the app's API base URL atthe proxy in dev/test only, tag server-side fetches (Next.js), add a smoke test,and verify record → replay.agent 会添加 skills,用 init 脚手架生成所有内容(配置、Playwright fixture、teardown、scripts,以及 —— 在 Next.js 上 —— 在你的 root layout 中加入 registerProxyFetch()),然后完成 init 自己无法从它打印的提示中猜到的接线。想要一份可直接复制的成品?参见示例。
或者手动接线
Section titled “或者手动接线”init 写入所有内容,但绝不覆盖任何已有文件:
test-proxy-recorder.config.tsplaywright.config.tsapp/layout.tsx # 仅 Next.js —— 加入 registerProxyFetch() 给 SSR fetch 打标e2e/fixtures.ts # record vs replaye2e/global-teardown.tspackage.json # + proxy / test:e2e 脚本1. 把应用的 API 指向代理
Section titled “1. 把应用的 API 指向代理”init 唯一猜不到的事情:哪个环境变量保存着你的 API 基础 URL。在录制器启用时把它指向代理,其余情况指向真实后端 —— 代理绝不在生产环境中运行:
// 只有 e2e 运行时,TEST_PROXY_RECORDER_ENABLED 才是 'true' 或 '1'。const recorderEnv = process.env.TEST_PROXY_RECORDER_ENABLED ?? '';const API_BASE = ['true', '1'].includes(recorderEnv) ? 'http://localhost:8100' // `init` 给出的代理地址 : 'https://api.example.com';2. 给服务端 fetch 打标(仅 Next.js)
Section titled “2. 给服务端 fetch 打标(仅 Next.js)”浏览器请求已经携带 recording-session id(由 Playwright 设置)。对于服务端 fetch(SSR、Server Components),在你的 root layout 中加一行让它们也带上标 —— init 会替你做这件事:
import { registerProxyFetch } from 'test-proxy-recorder/nextjs';
registerProxyFetch(); // production 下是 no-op,除非 TEST_PROXY_RECORDER_ENABLED=true
export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> </html> );}服务端调用用的是 axios?改用 registerProxyAxios(instance)。请针对 production build 录制(next build && next start),而不是 next dev。纯浏览器应用(SPA、扩展)可以跳过这一步。
3. 录制一次,永远回放
Section titled “3. 录制一次,永远回放”测试使用你的开发后端及其数据库。当 init 找到了应用的 production build(preview 脚本,或 Next.js 的 start)时,test:e2e 脚本会测试该 production build;而直接运行 npx playwright test 或 --ui 则使用你的开发服务器,因此你可以手动重新运行失败的测试,并在浏览器中复现 bug。录制之前,请先启动 dev,再用你自己的种子脚本(seed script)把开发数据库置于测试所期望的状态。
# 设置 RECORD_MODE=1 —— 捕获真实响应npm run test:e2e:record
# 然后提交录制内容;npm run test:e2e 会回放它们git add e2e/recordings/ && git commit -m "add e2e recordings"现在 CI 在后端关闭的情况下回放 —— 每次都是相同的响应。
更多细节:手动配置 · 工作原理 · AI agent skills。