You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright能否创建类似Cypress的自定义命令?如何封装测试钩子?

实现方案

Playwright 原生支持 Fixture 机制来封装公共逻辑,完全可以满足类似 Cypress 自定义命令的复用需求,具体实现如下:

步骤1:创建独立的公共封装模块

新建custom-test.js文件,把全局钩子、公共配置、自定义操作都封装到该模块中:

// custom-test.js
import { test as base } from '@playwright/test';
import { chromium } from '@playwright/test';

// 扩展原生test对象,自定义fixture
export const test = base.extend({
  // 封装持久化上下文逻辑
  context: async ({}, use) => {
    // 注意:Windows路径的反斜杠需要转义,或者直接用正斜杠避免报错
    const context = await chromium.launchPersistentContext(
      'C:/Users/User/AppData/Local/Microsoft/Edge/User Data/Default',
      {
        headless: false,
        executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
      }
    );
    await use(context);
    // 测试结束后自动关闭上下文
    await context.close();
  },
  // 封装页面初始化、自动打开目标地址逻辑
  page: async ({ context }, use) => {
    const page = await context.newPage();
    await page.goto('http://localhost:3000/');
    await use(page);
    // 测试结束后自动关闭页面
    await page.close();
  },
});

export { expect } from '@playwright/test';

步骤2:在测试用例中直接调用

测试文件无需再重复编写beforeEach/afterEach逻辑,直接导入封装好的test对象即可使用:

// 测试文件,比如sample.test.js
import { test, expect } from './custom-test.js';

test('Sample test', async ({ page }) => {
  await page.click('text=Open popup');
  await page.click('_react=Button >> nth=0');
  await page.click('text=Close popup');
});

扩展:封装自定义操作(等效于Cypress自定义命令)

如果需要复用常用的页面操作,直接在fixture中扩展page对象即可,示例如下:

// custom-test.js 中扩展page fixture
export const test = base.extend({
  context: async ({}, use) => {
    // 原有context逻辑不变
  },
  page: async ({ context }, use) => {
    const page = await context.newPage();
    await page.goto('http://localhost:3000/');

    // 新增自定义操作,所有测试用例都可以直接调用
    page.openPopup = async () => page.click('text=Open popup');
    page.closePopup = async () => page.click('text=Close popup');
    page.clickFirstReactBtn = async () => page.click('_react=Button >> nth=0');

    await use(page);
    await page.close();
  },
});

封装后测试用例可以简化为:

test('Sample test', async ({ page }) => {
  await page.openPopup();
  await page.clickFirstReactBtn();
  await page.closePopup();
});

内容的提问来源于stack exchange,提问作者in43sh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:45:04