DEV Community

Dennis Zhang
Dennis Zhang

Posted on • Edited on

cucumber-html-reporter生成测试报告表格

npm install cypress cypress-cucumber-preprocessor cucumber-html-reporter --save-dev
Enter fullscreen mode Exit fullscreen mode

cypress.config.js配置

const { defineConfig } = require('cypress')
const createBundler = require('@bahmutov/cypress-esbuild-preprocessor')
const addCucumberPreprocessorPlugin = require('@badeball/cypress-cucumber-preprocessor').addCucumberPreprocessorPlugin
const createEsbuildPlugin = require('@badeball/cypress-cucumber-preprocessor/esbuild').createEsbuildPlugin
const fs = require('fs');
const path = require('path');


module.exports = defineConfig({
  e2e: {
    async setupNodeEvents(on, config) {
      const bundler = createBundler({
        plugins: [createEsbuildPlugin(config)],
      })
      on('file:preprocessor', bundler)
      await addCucumberPreprocessorPlugin(on, config)

   // 自定义报告输出路径(例如,JSON 格式)
      on('after:run', (results) => {
        try {
          const jsonReportPath = path.join(config.projectRoot, 'report', 'cucumber_report.json');

          // 确保报告目录report存在
          const reportDir = path.dirname(jsonReportPath);
          if (!fs.existsSync(reportDir)) {
            fs.mkdirSync(reportDir, { recursive: true });
          }

          // 将测试结果写入 JSON 文件
          fs.writeFileSync(jsonReportPath, JSON.stringify(results, null, 2));
        } catch (err) {
          console.error('Failed to write the report file:', err);
        }
      });

      return config
    },
    specPattern: 'cypress/e2e/**/*.feature', // 设置 .feature 文件的路径
  },
})
Enter fullscreen mode Exit fullscreen mode

在 package.json 的 scripts 部分

"scripts": {
  "test": "cypress run",
  "posttest": "node generate-html-report.js",
  "report":"npm run test && node convert-report.js && node generate-html-report.js "
}

Enter fullscreen mode Exit fullscreen mode

convert-report.js 脚本转换json

const fs = require('fs');

const inputFilePath = 'report/cucumber_report.json'; // Cypress 生成的 JSON 报告
const outputFilePath = 'report/converted_report.json'; // 转换后的 JSON 文件

fs.readFile(inputFilePath, 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the input file:', err);
    return;
  }

  let results;
  try {
    results = JSON.parse(data);
  } catch (err) {
    console.error('Error parsing JSON:', err);
    return;
  }

  const converted = {
    features: results.runs.map(run => ({
      keyword: "Feature",
      name: run.spec.name,
      uri: run.spec.relative,
      elements: run.tests.map(test => ({
        keyword: "Scenario",
        name: test.title.join(' '),
        steps: test.steps.map(step => ({
          keyword: "Step",
          name: step.name,
          result: {
            status: step.state,
            duration: step.duration
          }
        }))
      }))
    }))
  };

  fs.writeFile(outputFilePath, JSON.stringify(converted, null, 2), err => {
    if (err) {
      console.error('Error writing the output file:', err);
    } else {
      console.log('Report converted successfully!');
    }
  });
});


Enter fullscreen mode Exit fullscreen mode

cucumber-html-reporter 生成 HTML 报告

创建一个名为 generate-html-report.js 的文件

const reporter = require('cucumber-html-reporter');

const options = {
  theme: 'bootstrap',
  jsonFile: 'report/converted_report.json', // 你的 JSON 报告的路径
  output: 'report/cucumber_report.html',   // 生成的 HTML 报告的路径
  reportSuiteAsScenarios: true,
  launchReport: true,
  metadata: {
    "App Version": "0.1.0",
    "Test Environment": "STAGING",
    "Browser": "Chrome  91.0.4472.124",
    "Platform": "Windows 10",
    "Parallel": "Scenarios",
    "Executed": "Remote"
  }
};

reporter.generate(options);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)