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

如何在Azure DevOps中配置Lighthouse测试断言并集成至构建流水线

集成Lighthouse检查到Azure DevOps构建流水线并设置分数断言

一、准备Lighthouse测试与断言脚本

先创建一个Node.js脚本(命名为lighthouse-audit.js),用于执行测试并验证分数阈值:

const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
const fs = require('fs');

// 配置待测试的关键链接及对应分数阈值
const auditTargets = [
  {
    url: 'https://your-key-page-1.com',
    scoreThresholds: { performance: 90, accessibility: 95, seo: 85 }
  },
  {
    url: 'https://your-key-page-2.com',
    scoreThresholds: { performance: 85, accessibility: 90 }
  }
];

async function runAudits() {
  let allChecksPassed = true;

  for (const target of auditTargets) {
    console.log(`=== 开始测试页面: ${target.url} ===`);
    
    // 启动无头Chrome
    const chromeInstance = await chromeLauncher.launch({ chromeFlags: ['--headless', '--no-sandbox'] });
    const lighthouseOptions = { logLevel: 'info', output: 'json', port: chromeInstance.port };
    
    // 执行Lighthouse检查
    const auditResult = await lighthouse(target.url, lighthouseOptions);
    
    // 保存结果文件(可选,用于后续排查)
    const resultFileName = `lighthouse-result-${target.url.replace(/[^a-z0-9]/gi, '-')}.json`;
    fs.writeFileSync(resultFileName, auditResult.report);
    
    // 验证分数是否达标
    const categoryScores = auditResult.lhr.categories;
    for (const [category, threshold] of Object.entries(target.scoreThresholds)) {
      const currentScore = Math.round(categoryScores[category].score * 100);
      console.log(`${category} 分数: ${currentScore}/100 (阈值: ${threshold})`);
      
      if (currentScore < threshold) {
        console.error(`❌ ${category} 分数未达标,当前分数(${currentScore})低于阈值(${threshold})`);
        allChecksPassed = false;
      }
    }

    await chromeInstance.kill();
    console.log(`=== 页面 ${target.url} 测试完成 ===\n`);
  }

  // 断言失败则终止流水线
  if (!allChecksPassed) {
    console.error('❌ 部分Lighthouse检查未通过,流水线终止');
    process.exit(1);
  } else {
    console.log('✅ 所有Lighthouse检查均通过');
  }
}

// 执行测试,捕获异常并终止流水线
runAudits().catch(err => {
  console.error('❌ Lighthouse测试执行异常:', err);
  process.exit(1);
});

二、集成到Azure DevOps YAML流水线

在你的流水线YAML文件中添加以下步骤,实现自动化检查:

1. 配置Node.js环境

- task: NodeTool@0
  inputs:
    versionSpec: '20.x' # 根据项目需求选择合适的Node.js版本
  displayName: '安装Node.js环境'

2. 安装Lighthouse依赖

- script: |
    npm install lighthouse chrome-launcher
  displayName: '安装Lighthouse测试依赖'

3. 执行Lighthouse检查(失败即终止流水线)

- script: |
    node lighthouse-audit.js
  displayName: '执行Lighthouse合规性检查'
  continueOnError: false # 强制检查失败时终止流水线

4. (可选)发布测试结果到Azure DevOps

如果需要在Azure DevOps的测试面板查看详细结果,可以将JSON结果转为JUnit格式并发布:

- script: |
    npm install -g lighthouse-junit
    lighthouse-junit ./lighthouse-result-*.json -o ./lighthouse-test-results.xml
  displayName: '转换Lighthouse结果为JUnit格式'
  condition: succeededOrFailed() # 无论测试成败都执行转换

- task: PublishTestResults@2
  inputs:
    testResultsFormat: 'JUnit'
    testResultsFiles: './lighthouse-test-results.xml'
    failTaskOnFailedTests: true # 测试失败时终止流水线
  displayName: '发布Lighthouse测试结果'

三、核心逻辑说明

  • 流水线终止机制:通过脚本中process.exit(1)主动抛出错误,配合流水线步骤的continueOnError: false或failTaskOnFailedTests: true,确保任一检查失败时立即终止流水线。
  • 分数断言配置:在auditTargets数组中,为每个页面的性能、可访问性、SEO等类别设置最低分数阈值,脚本会自动对比验证。
  • 无头模式适配:Chrome启动时添加--headless和--no-sandbox参数,适配Azure DevOps流水线的无界面运行环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 07:55:24