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

如何简化ES6中含多try-catch的Puppeteer自动化测试代码?

简化Puppeteer+Mocha自动化测试函数(减少try-catch并优化ES6写法)

你可以通过合并错误捕获逻辑、简化冗余代码、使用ES6新特性来大幅减少try-catch块数量,同时让代码更简洁易读。以下是优化后的版本:

async function elementAttributeShouldBe(page, selector, attribute, attributeValue, fullMatch = false) {
  let currentAttrValue;
  try {
    // 获取属性值,用可选链避免元素不存在时直接报错
    currentAttrValue = await page.evaluate((sel, attr) => {
      const element = document.querySelector(sel);
      return element?.getAttribute(attr);
    }, selector, attribute);

    // 统一转换为小写,避免重复调用方法
    const normalizedCurrent = currentAttrValue?.toLocaleLowerCase();
    const normalizedExpected = attributeValue.toLocaleLowerCase();

    // 提前校验属性值是否存在
    if (!normalizedCurrent) {
      throw new Error(`元素 ${selector} 的属性 ${attribute} 为空或不存在`);
    }

    // 直接判断匹配结果,去掉冗余的result变量
    const isMatch = fullMatch 
      ? normalizedCurrent === normalizedExpected 
      : normalizedCurrent.includes(normalizedExpected);

    // 断言匹配结果,自带明确错误信息
    assert.isTrue(isMatch, `元素 ${selector} 的属性 ${attribute} 值不符合预期:实际值「${currentAttrValue}」,预期${fullMatch ? "完全匹配" : "包含"}「${attributeValue}」`);
  } catch (error) {
    // 统一处理所有错误,优化错误提示格式
    const baseMsg = `验证元素属性失败:选择器「${selector}」,属性「${attribute}」`;
    if (error.message.includes('getAttribute') || error.message.includes('为空或不存在')) {
      throw new Error(`${baseMsg},无法获取属性值`);
    }
    throw new Error(`${baseMsg},${error.message}`);
  }
}

主要优化点:

  • 合并所有try-catch为一个:把属性获取、格式转换、断言逻辑全部放入单个try块,所有错误统一在一个catch里处理,直接砍掉原代码中2个多余的try-catch块。
  • 使用ES6可选链?.:避免元素不存在或属性值为null时调用方法抛出错误,减少不必要的错误分支。
  • 去掉冗余变量:删除了result变量,直接通过布尔表达式判断匹配结果,代码更紧凑。
  • 提前归一化处理:只做一次大小写转换,避免重复调用toLocaleLowerCase(),提升效率同时减少代码重复。
  • 优化错误提示:统一错误信息格式,调试时更容易定位问题;给fullMatch设置默认值,调用时可省略该参数。
  • 规范命名:调整函数和变量名为小驼峰格式,符合JS常规命名规范,可读性更强。

为什么能减少try-catch?

原代码的多个try-catch是为了隔离不同阶段的错误,但实际上这些错误都属于「属性验证流程中的异常」,完全可以合并到同一个错误捕获逻辑里。通过提前做null/undefined校验、使用可选链避免潜在报错,还能进一步减少需要捕获的错误场景,让代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 07:45:26