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

Playwright+TypeScript中document未定义错误:SEO标题顺序检测问题

解决Playwright+TypeScript中document is not defined错误的标题层级检测方案

你遇到的ReferenceError: document is not defined是因为Playwright测试代码运行在Node.js环境中,而document是浏览器端专属的DOM对象,Node.js环境无法直接访问。要操作页面DOM,必须通过Playwright的page.evaluate()方法把代码注入到浏览器上下文执行。

以下是修复后的完整代码,同时优化了SEO层级检测逻辑,让测试在层级错误时直接失败:

async assertHeadingsOrder2() {
  await test.step('Test html header structure for catalog page', async () => {
    // 通过page.evaluate在浏览器上下文执行DOM操作和层级检测
    const isHierarchyValid = await page.evaluate(() => {
      const headingTags = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
      const hierarchy: number[] = [];

      for (const heading of headingTags) {
        const tagName = heading.tagName.toLowerCase();
        const level = parseInt(tagName.charAt(1), 10);

        // 验证层级:当前层级不能比上一层级大超过1(比如不能直接从h1跳到h3)
        if (hierarchy.length > 0) {
          const lastLevel = hierarchy[hierarchy.length - 1];
          if (level > lastLevel + 1) {
            console.error(`Invalid heading hierarchy: ${tagName} follows ${'h' + lastLevel}, which skips a level`);
            return false;
          }
        }

        hierarchy.push(level);
      }

      console.log('Valid heading hierarchy:', hierarchy.map(l => `h${l}`).join(' > '));
      return true;
    });

    // 断言层级有效,否则测试失败
    expect(isHierarchyValid).toBe(true);
  });
}

关键改动说明:

  • 用page.evaluate()包裹所有DOM相关代码,确保在浏览器环境中执行,能正常访问document
  • 优化层级检测逻辑:跟踪每一个标题的层级,检查是否存在跳级(比如h1之后直接出现h3)
  • 将检测结果返回至Node.js环境,用Playwright的expect断言确保测试在层级错误时失败
  • 移除了不必要的// eslint-disable-next-line @typescript-eslint/require-await注释,因为现在test.step内部是真正的异步操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:17:14