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

Jest-Puppeteer测试Chrome扩展:用例通过但套件因目标站点报错失败

解决Jest-Puppeteer测试外部站点时套件失败的问题

问题背景

开发Chrome扩展时,需测试一个无法控制的外部站点。该站点存在大量内部错误,导致Jest-Puppeteer测试套件失败,但测试用例本身执行正常、Puppeteer流程也能正常运行。尝试定义缺失的引用会导致站点功能完全失效;添加多种错误监听器也无法解决——测试用例全部通过,但测试套件仍失败。

报错信息

● Test suite failed to run

    ReferenceError: module is not defined


  ● Test suite failed to run

    ReferenceError: getItemKeyValue is not defined

  ● Test suite failed to run

    TypeError: Cannot read properties of undefined (reading 'template')


  ● Test suite failed to run

    ReferenceError: global is not defined

Test Suites: 1 failed, 1 total
Tests:       4 passed, 4 total

已尝试的处理代码

await page.evaluateOnNewDocument(() => {
    window.addEventListener('error', event => {
      console.warn('Error intercepted:', event.message);
      event.preventDefault(); // Prevent the default handler
    });
  });

  //This error captures and gets past page errors, but doesn't work on the reference errors 
  page.on('pageerror', error => {
    if (error instanceof ReferenceError) {
      // Handle ReferenceError differently
      console.log('ref error', error)

    } else {
      // Handle or log other types of errors
      console.error('Page error:', error.message);
    }
  });

  // Stops all progress, but technically can run the suite :(
  await page.evaluateOnNewDocument(() => {
    window.getItemKeyValue = window.getItemKeyValue || function () { }; // Stubbing the function
    window.global = window; // Defining 'global'
  });

解决方案

1. 精准注入缺失的全局依赖

在页面加载前,用evaluateOnNewDocument注入站点缺失的全局变量和函数,保留已存在的项,避免破坏站点原有功能:

await page.evaluateOnNewDocument(() => {
  // 注入缺失的全局变量
  window.module = window.module || {};
  window.global = window.global || window;
  
  // 注入缺失的函数,返回合理默认值避免功能异常
  window.getItemKeyValue = window.getItemKeyValue || () => null;
  
  // 处理template属性错误,假设是某个全局对象的属性,按需调整
  window.templateHost = window.templateHost || { template: {} };
});

2. 拦截页面错误阻止套件失败

即使注入了依赖,仍可能有未预见的错误,需拦截页面错误,避免它们触发Jest的套件失败机制:

// 拦截所有页面错误,仅做日志记录不向上抛出
page.on('pageerror', (error) => {
  console.warn('忽略站点内部错误:', error.message);
});

// 可选:拦截控制台错误信息,避免干扰测试日志
page.on('console', (msg) => {
  if (msg.type() === 'error') {
    console.warn('站点控制台错误:', msg.text());
  }
});

3. 忽略未处理的Promise拒绝

如果站点存在未处理的Promise拒绝,也可能导致套件失败,可在测试文件顶部添加:

process.on('unhandledRejection', () => {});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 13:55:03