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

Playwright页面标题断言报错:ReferenceError: expect未定义

问题解决:Playwright测试中expect is not defined及标题断言错误

1. 解决ReferenceError: expect is not defined

Playwright的断言方法expect需要从官方测试库中显式导入,你的代码缺少这一关键步骤。在测试文件顶部添加导入语句:

  • CommonJS语法:
const { test, expect } = require('@playwright/test');
  • ES模块语法:
import { test, expect } from '@playwright/test';

2. 修复标题断言不匹配问题

从控制台输出可见,页面实际标题是Wikipedia(首字母大写),但你的断言写的是小写的"wikipedia",这会导致后续断言失败。可按以下方式修改:

  • 精确匹配(推荐,符合页面实际标题):
await expect(page).toHaveTitle("Wikipedia");
  • 忽略大小写模糊匹配:
await expect(page).toHaveTitle(/wikipedia/i);

完整修正后的测试代码

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

test('page playwright test', async ({ page }) => {
    await page.goto("https://www.wikipedia.org");
    console.log(await page.title());
    await expect(page).toHaveTitle("Wikipedia");
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:07:09