使用 Playwright 为 WooCommerce 结账流程编写 E2E 测试并参数化支付?

解读

在国内 WooCommerce 项目里,支付通道(微信、支付宝、银联、PayPal 等)经常切换,测试环境又必须隔离沙箱与正式网关。面试官想确认三件事:

  1. 你是否能把 WooCommerce 结账的 6 大步骤(商品页→购物车→结算→填写账单→选择支付→支付回调)用 Playwright 完整串起来;
  2. 能否用 参数化 把“支付网关、卡号、手机号、金额”抽离到 JSON/CSV,实现一套脚本覆盖所有支付场景;
  3. 是否具备 失败重跑、数据清理、并发隔离 等工程化意识,避免测试用例互相污染。

知识点

  • Playwright test 钩子(test.beforeEach、test.afterAll)与 worker 隔离
  • data-driven 模式:test.describe.configure({ retries: 2 }) + test.step 读取 fixtures/payment.json
  • WooCommerce REST API 预置订单(wp-json/wc/v3/orders)与 消费者密钥权限
  • 结算字段映射:billing_first_name、billing_phone(需兼容大陆 11 位手机号正则)
  • 支付网关 Hook:woocommerce_available_payment_gateways 过滤,测试环境动态注入 “cod、bacs, alipay_wap, wechatpay”
  • 沙箱回调:支付宝 notify_url、微信 native 二维码,Playwright 需 mock 第三方服务器 或使用 ngrok 内网穿透
  • 断言维度:库存扣减、order_status=processing、postmeta _paid_date 非空、微信支付订单号写入 _transaction_id
  • 性能卡点:关闭 WP_CRON 与邮件,wp-config.php 加 define('DISABLE_WP_CRON', true) 以及 object-cache.php 屏蔽外部请求
  • CI 集成:GitHub Actions 服务容器 mysql:8.0 + wordpress:6.5,Playwright 1.44 缓存 /ms-playwright 目录,并发 shard 策略

答案

以下示例基于 Playwright 1.44 + TypeScript,把支付参数抽到 fixtures/payment.json,实现 3 条用例(货到付款、支付宝、微信):

  1. 项目结构
    tests
    ├─ fixtures
    │ ├─ payment.json
    │ └─ global-setup.ts
    ├─ pages
    │ ├─ cart.page.ts
    │ ├─ checkout.page.ts
    │ └─ payment-gateways
    │ ├─ alipay.ts
    │ └─ wechat.ts
    ├─ e2e
    │ └─ checkout.spec.ts
    playwright.config.ts

  2. fixtures/payment.json(敏感字段用环境变量占位)
    [ { "name": "cod", "gateway_id": "cod", "card": null, "amount": "0.01", "expected_status": "processing" }, { "name": "alipay", "gateway_id": "alipay_wap", "card": null, "amount": "0.02", "expected_status": "processing" }, { "name": "wechat", "gateway_id": "wechatpay", "card": null, "amount": "0.03", "expected_status": "processing" } ]

  3. global-setup.ts(一次性创建测试用户与商品)
    import { request } from '@playwright/test'; async function globalSetup() { const context = await request.newContext({ baseURL: process.env.WP_URL, extraHTTPHeaders: { Authorization: 'Basic ' + Buffer.from(${process.env.WP_KEY}:${process.env.WP_SECRET}).toString('base64') } }); // 创建简单商品 await context.post('/wp-json/wc/v3/products', { data: { name: '面试测试商品', type: 'simple', regular_price: '0.01', manage_stock: true, stock_quantity: 999 } }); } export default globalSetup;

  4. checkout.page.ts(封装结算页)
    export class CheckoutPage { constructor(private page) {} async fillBilling(data: { name: string; phone: string; address: string }) { await this.page.locator('#billing_first_name').fill(data.name); await this.page.locator('#billing_phone').fill(data.phone); await this.page.locator('#billing_address_1').fill(data.address); } async selectPayment(gatewayId: string) { await this.page.locator(input[value="${gatewayId}"]).check(); } async placeOrder() { await this.page.locator('#place_order').click(); } async waitForThankYou() { await this.page.waitForURL(//checkout/order-received//); } }

  5. checkout.spec.ts(参数化核心)
    import { test, expect } from '@playwright/test'; import paymentCases from '../fixtures/payment.json'; import { CheckoutPage } from '../pages/checkout.page'; import { AlipayHandler } from '../pages/payment-gateways/alipay'; import { WechatHandler } from '../pages/payment-gateways/wechat';

for (const pay of paymentCases) { test(结账支付:${pay.name}, async ({ page, context }) => { await test.step('添加商品到购物车', async () => { await page.goto('/product/面试测试商品'); await page.locator('text=加入购物车').click(); await page.locator('text=查看购物车').click(); await page.locator('text=前往结账').click(); });

const checkout = new CheckoutPage(page);
await test.step('填写账单信息', async () => {
  await checkout.fillBilling({ name: '张三', phone: '13800138000', address: '广东省深圳市南山区' });
});

await test.step('选择支付方式并下单', async () => {
  await checkout.selectPayment(pay.gateway_id);
  await checkout.placeOrder();
});

await test.step('完成第三方支付', async () => {
  if (pay.gateway_id === 'alipay_wap') {
    const alipay = new AlipayHandler(page, context);
    await alipay.mockSandbox(); // 本地 mock 掉支付宝网页,直接返回 success
  } else if (pay.gateway_id === 'wechatpay') {
    const wechat = new WechatHandler(page, context);
    await wechat.scanQrcodeAndMock(); // 模拟扫码支付回调
  }
});

await test.step('断言订单状态', async () => {
  await checkout.waitForThankYou();
  const orderId = checkout.page.url().match(/\/(\d+)\//)[1];
  const api = context.request;
  const res = await api.get(`/wp-json/wc/v3/orders/${orderId}`);
  const json = await res.json();
  expect(json.status).toBe(pay.expected_status);
  expect(parseFloat(json.total)).toBe(parseFloat(pay.amount));
});

}); }

  1. playwright.config.ts 关键片段
    import { defineConfig } from '@playwright/test'; export default defineConfig({ testDir: './tests/e2e', fullyParallel: true, workers: 4, retries: 2, globalSetup: require.resolve('./tests/fixtures/global-setup.ts'), use: { baseURL: process.env.WP_URL || 'http://wp.test', trace: 'retain-on-failure', screenshot: 'only-on-failure' } });

  2. 运行与报告
    CI 环境变量
    WP_URL=https://wp.test
    WP_KEY=ck_xxx
    WP_SECRET=cs_xxx
    npx playwright test --grep "@smoke" --reporter=html,github
    测试通过后在 playwright-report/index.html 查看 trace 时间轴,失败自动重跑并保留请求头与响应体,方便定位支付回调 400 问题。

拓展思考

  1. 并发隔离:若微信支付回调依赖固定 notify_url,CI 中可用 ngrok 随机子域名 并写入 wp_options 的 wechatpay_notify_url,实现多 job 并行无冲突。
  2. 性能基线:在结账流程前后采集 wp-db-queries 指标,Playwright 通过 page.evaluate(() => performance.memory) 拿到 JS 堆栈,结合 New Relic 或 Query Monitor 插件,断言 SQL 查询 < 80 条,内存峰值 < 128 M。
  3. 安全回归:利用 WP-CLI 一键切换“强制 SSL checkout”,测试脚本自动检测 Mixed Content;同时把 woocommerce_gateway_{id}_process_payment 动作挂错场景(如签名失败、重复通知)做成 异常参数化用例,确保订单不会重复入账。
  4. 回归提速:把 WooCommerce 结算页 全静态化 到 Redis,Playwright 启动前预置 30 条订单缓存,测试时间从 90 s 降到 18 s,满足 每日多版本回归 的敏捷节奏。