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

如何在Playwright JS中使用expect?附Puppeteer代码转写需求

在Playwright JS中使用expect及代码迁移指南

一、Playwright内置expect的基础用法

Playwright自带专为浏览器自动化场景优化的断言库,无需额外引入Chai。核心优势是自动重试断言,直到条件满足或超时,省去手动处理元素加载等待的麻烦。

使用前需从@playwright/test导入:

const { expect } = require('@playwright/test');

常见断言示例:

  • 检查元素包含文本:await expect(page.locator('.selector')).toContainText('目标文本')
  • 检查元素文本不包含指定内容:await expect(page.locator('.selector')).not.toContainText('排除文本')
  • 检查元素可见:await expect(page.locator('.selector')).toBeVisible()

二、Puppeteer+Chai代码迁移为Playwright代码

以下是你提供的Puppeteer代码对应的Playwright版本,同时标注关键改动:

迁移后的Playwright代码

const { chromium, expect } = require('@playwright/test');

(async () => {
  // 启动浏览器,参数和Puppeteer基本一致
  const browser = await chromium.launch({
    headless: false,
    slowMo: 500, // 保留原需求的放慢操作速度设置
  });
  
  // Playwright最佳实践:先创建上下文再生成页面,隔离页面状态
  const context = await browser.newContext();
  const page = await context.newPage();

  // 打开目标页面,无需额外等待导航完成——page.goto默认等待页面加载完毕
  await page.goto('https://www.test.com');

  // 截图保存,参数和Puppeteer一致
  await page.screenshot({ path: 'navigation.jpg' });

  // 方式1:先获取文本再断言(和原代码逻辑对齐)
  const text = await page.locator('.top--right').textContent();
  expect(text).not.toContain('top-bar');

  // 方式2:推荐写法——直接对元素定位器断言,自动等待元素加载完成
  // await expect(page.locator('.top--right')).not.toContainText('top-bar');

  console.log('Navigation is deployed');

  // 关闭浏览器
  await browser.close();
})();

关键改动说明

  1. 依赖替换:用@playwright/test的chromium和内置expect替代Puppeteer与Chai
  2. 页面创建流程:新增browser.newContext(),这是Playwright的最佳实践,用于隔离不同页面的cookie、localStorage等状态
  3. 导航逻辑简化:移除navigationPromise,page.goto默认等待页面加载完成(等价于Puppeteer的waitForNavigation)
  4. 元素定位优化:用page.locator()替代page.$eval(),locator是Playwright推荐的定位方式,支持自动等待元素出现、稳定,减少因元素未加载导致的断言失败
  5. 断言方式升级:推荐直接对locator使用断言,无需手动获取文本,Playwright会自动重试直到断言条件满足

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 21:35:21