代理
.mock.jsonNext.js / TanStack Start SSR → 代理 → 真实 API
适用于服务器调用 API 的全栈应用。
位于你的服务器与 API 之间。录制服务端请求:Server Component 和 SSR 发出的 fetch、route handler,以及你的 backend-for-frontend 所调用的任何内容。
每个测试的服务端请求都带有该测试的 id,因此并行运行的测试绝不会共用同一份录制。
录制一次。
永久回放。
录制本地 Playwright 运行期间你的应用收到的 API 响应(包括 WebSocket),随后在 CI 上回放,后端保持关闭。
npm i -D test-proxy-recorder 在 GitHub 上加星v2.1.0 · MIT · TypeScript · Node ≥ 20 · Next.js 与 TanStack Start SSR、SPA、Chrome 扩展、WebSocket
REC
saved todos__adds-a-todo.mock.json
REPLAY
200 OK · 3 ms · from disk
一次 Playwright 运行把真实响应录制到磁盘;翻转到回放,同一套件在后端关闭的情况下通过。
请求从两个地方发出,所以有两种录制方式,并且两种方式下代理进程都会运行。发往代理的一切请求(服务端 fetch、经由与服务器共用的 API 基础 URL 发出的浏览器调用、WebSocket)都从该测试的 .mock.json 回放。发往其他主机、且匹配你的 fixture 中 url 模式的浏览器调用,则从该测试的 .har 回放。
.mock.jsonNext.js / TanStack Start SSR → 代理 → 真实 API
适用于服务器调用 API 的全栈应用。
位于你的服务器与 API 之间。录制服务端请求:Server Component 和 SSR 发出的 fetch、route handler,以及你的 backend-for-frontend 所调用的任何内容。
每个测试的服务端请求都带有该测试的 id,因此并行运行的测试绝不会共用同一份录制。
.har浏览器 → HAR 拦截 → 真实 API
适用于 SPA、扩展和纯浏览器应用。
在浏览器内部进行拦截,并保存一个 HTTP Archive(HAR)文件。录制客户端 fetch 调用、Chrome 扩展 API 流量、分析数据和第三方 API,只要它们匹配你的 fixture 中的 url 模式。
与直接使用 routeFromHAR 相比,它为每个测试单独生成一个 HAR,并涂抹认证 header。
npx playwright test -g "adds a todo" 只会重新录制这一个测试。测试在并行 worker 上录制,就像回放时一样,除非它们共用同一个数据库或账号。x-test-rcrd-id header,而 registerProxyFetch() 会把它复制到你的服务器自己发出的 fetch 上。代理读取这个 id,把每个测试录制到它自己的文件中,并从该文件回放,即使测试并行运行也是如此。{ "id": "todos__adds-a-todo", "recordings": [ { "request": { "method": "POST", "url": "/todos", "headers": { "authorization": "[REDACTED]", "x-test-rcrd-id": "todos__adds-a-todo" }, "body": "{\"title\":\"Buy groceries\"}" }, "response": { "statusCode": 201, "body": "{\"id\":7,\"title\":\"Buy groceries\",\"done\":false}" }, "key": "POST_todos.json", "sequence": 0 } ]}不同的 mock 工具擅长不同的工作。下面的组合 —— 跨 SSR、浏览器和 WebSocket 录制真实流量,且不手写 mock —— 正是其他工具留下的空白。
| 特性 | test-proxy-recorder | Playwright routeFromHAR | MSW | Polly.js | playwright-network-cache | Mocky Balboa |
|---|---|---|---|---|---|---|
| 录制真实流量 | 是 | 是 | 否 | 是 | 是 | 否 |
| 服务端(SSR) | 是 | 否 | 是 | 部分 | 否 | 是 |
| 浏览器端 | 是 | 是 | 是 | 是 | 是 | 是 |
| WebSocket | 是 | 否 | 是 | 否 | 否 | 否 |
| Playwright 原生 | 是 | 是 | 是 | 否 | 是 | 是 |
| 维护中 | 是 | 是 | 是 | 否 | 是 | 是 |
Polly.js 在它所运行的进程内部录制,所以对于服务端请求,它必须运行在你的应用服务器内部。MSW 和 Mocky Balboa 也能 mock 服务端请求,但响应要你自己编写。完整的对比(附来源,以及何时该选用其他工具)见 文档。
代价是首次搭建比纯浏览器端的工具更费事:需要在测试旁运行一个代理进程;对于服务端请求,测试运行期间还要把应用的 API 基础 URL 指向它。
通过 Cognito、Auth0、Clerk 或 WorkOS 登录 —— 每次运行都真实进行。只有你应用的 API 会被录制;认证保持在线,你的数据离线处理。
// e2e/auth.setup.ts — log in for real, once. Never recorded.import { test as setup } from '@playwright/test';import { setProxyMode } from 'test-proxy-recorder';
setup('authenticate', async ({ page }) => { await setProxyMode('transparent'); // login bypasses the recorder await page.goto('/login'); await page.getByTestId('email').fill(process.env.TEST_EMAIL!); await page.getByTestId('password').fill(process.env.TEST_PASSWORD!); await page.getByTestId('signinButton').click(); await page.waitForURL('/dashboard');
// Reused by every test — they start already signed in. await page.context().storageState({ path: 'e2e/.auth/state.json' });});AWS Cognito 示例 → TanStack Start 上的 Cognito → Mock 认证(无需云账号) →
用一条命令脚手架生成所有内容,把 API 指向代理,然后录制并提交。纯浏览器应用? init 会替你跳过 SSR 步骤。
registerProxyFetch() 函数。它会把测试的 id 复制到每个服务端 fetch 上;除非设置了 TEST_PROXY_RECORDER_ENABLED,否则它在生产环境中什么也不做。把它粘贴到 Claude Code、Cursor 或其他编码 agent 中。它会先运行 @tanstack/intent,在 agent 的配置文件(例如 CLAUDE.md)中加入指引,让 agent 加载本库的设置技能。然后它会安装这个包,从应用的配置中找到你的后端 URL,运行 init 并根据它的输出完成剩下的接入工作。
Set up test-proxy-recorder for end-to-end tests in this project, then follow the instructions that `init` prints. Run these commands:
npx @tanstack/intent@latest install npm install --save-dev test-proxy-recorder
Then run init, passing this project's backend API base URL as the target — find it yourself from the app's env/config (the URL the app calls in dev); don't assume 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 at the proxy in dev/test only, tag server-side fetches (Next.js), add a smoke test, and verify record → replay.init 会写入代理配置、一个 Playwright fixture、一个全局 teardown、 package.json 脚本,并(在 Next.js 上)把 SSR fetch 打标接入你的 root layout —— 全程非破坏性。
npm install --save-dev test-proxy-recorder# localhost:3002 is your API, 8100 is the proxy. Flags are optional.npx test-proxy-recorder init http://localhost:3002 --port 8100 --dir ./e2e/recordings唯一 init 猜不到的事情:哪个环境变量保存着你的 API 基础 URL。在录制器启用时把它指向代理,其余情况指向真实后端 —— 代理绝不在生产环境中运行。
// The proxy during e2e runs, the real backend everywhere else.// TEST_PROXY_RECORDER_ENABLED is 'true' or '1' for the e2e run only.const recorderEnv = process.env.TEST_PROXY_RECORDER_ENABLED ?? '';const API_BASE = ['true', '1'].includes(recorderEnv) ? 'http://localhost:8100' // proxy address from `init` : 'https://api.example.com';
const res = await fetch(`${API_BASE}/todos`);在 Next.js 上, init 还会添加 registerProxyFetch() 到你的 root layout,给服务端的 fetch 调用打标 —— 在生产环境中是 no-op。
纯浏览器应用?如果应用不打开 WebSocket,可以跳过这一步;WebSocket 只有连接到代理的地址时才会被录制。
设置 MODE = 'record',针对真实 API 运行一次,然后翻转到 'replay' 并提交。录制内容存放在 git 中 —— 这正是 CI 具有确定性的原因。不要 gitignore 它们。
import { test, expect } from '@playwright/test';import { playwrightProxy } from 'test-proxy-recorder';
// Full-stack: the browser also talks to the proxy, so match its URL.// Browser-only app? Match your real API domain, e.g. /api\.example\.com/.const CLIENT_SIDE_URL = /localhost:8100/;
// 'record' hits the real API and saves responses.// 'replay' serves them from disk — no network needed.const MODE = 'replay' as const;
test.beforeEach(async ({ page }, testInfo) => { await playwrightProxy.before(page, testInfo, MODE, { url: CLIENT_SIDE_URL });});
test('homepage loads', async ({ page }) => { await page.goto('/'); await expect(page.getByText('Welcome')).toBeVisible();});url 模式(即你的 fixture 传给 before() 的模式),但不在 HAR 中,Playwright 会中止它;其他调用则会发往网络。teardown()。CI 中没有运行后端时,这样的调用会失败,而不是通过。 会话超时与 teardown →page.route() 在 before() 之后注册的路由处理函数会覆盖录制。服务端响应则在 .mock.json 文件中编辑。 强制指定响应 →你的 API 已经给出正确答案。把它们录制下来。
npm i -D test-proxy-recorder 在 GitHub 上加星如果它帮你省下了一个下午,点一颗 star 只要一秒钟 —— 这就是下一个人找到它的方式,也是在告诉一个独自维护的人继续做下去。遇到卡壳或有想法? 提交 issue 或 加入 Discord。