当 play 函数测试失败,如何自动生成带截图的 JUnit 报告

解读

在国内 CI/CD 流程中,JUnit XML 报告是 Jenkins、GitLab CI、钉钉/飞书通知等系统识别测试结果的“通用货币”。Storybook 的 @storybook/addon-interactions 提供的 play 函数本质上是运行在浏览器里的测试代码,一旦断言失败,默认只会在浏览器控制台或 Storybook UI 里报错,不会自动产出 JUnit 文件,更不会附带失败截图。
面试官问“如何自动生成带截图的 JUnit 报告”,核心想验证两点:

  1. 你是否理解 Storybook 测试链路(build → test-runner → jest → playwright/cypress → 报告)。
  2. 你是否能把“浏览器端失败”映射到“Node 端报告”,并把截图路径写进 JUnit XML,让国内常见的 Jenkins 流水线能直接解析、归档、钉钉推送。

知识点

  1. @storybook/test-runner:官方 Jest 封装,负责把每个 story 当测试用例跑;可注入自定义 Jest 环境。
  2. jest-junit:国内最常用的 JUnit XML 生成器,支持 <failure>、<system-out>、<system-err>、<properties> 等标准字段。
  3. Playwright 的 page.screenshot():test-runner 默认使用 playwright,可在 afterEach 钩子中捕获失败瞬间。
  4. Jest 钩子与自定义 reporter:通过环境变量 JEST_IMAGE_SNAPSHOT_OUTPUT_DIR 或自定义 reporterPath 把截图绝对路径写进 junit.xml。
  5. CI 路径约定:国内 Jenkins 一般把 WORKSPACE/test−results/junit.xml∗∗与∗∗{WORKSPACE}/test-results/junit.xml** 与 **{WORKSPACE}/test-results/screenshots/ 作为归档目录,必须保证路径在 XML 中可访问。
  6. 失败判定:play 函数抛出的错误会被 test-runner 捕获,test.fn.errors[0].message 即为失败原因,需要原样写进 <failure> 节点。

答案

步骤如下,可直接落地到国内 GitLab-CI + Jenkins 环境:

  1. 安装依赖

    pnpm add -D @storybook/test-runner jest-junit playwright sharp
    
  2. 在项目根目录新建 jest.config.storybook.js

    module.exports = {
      rootDir: '.',
      testMatch: ['**/*.stories.[jt]s?(x)'],
      testEnvironment: '@storybook/test-runner/playwright',
      setupFilesAfterEnv: ['<rootDir>.storybook/jest-setup.js'],
      reporters: [
        'default',
        ['jest-junit', {
          outputDirectory: 'test-results',
          outputName: 'junit.xml',
          // 把截图路径写进 properties,方便 Jenkins 解析
          addFileAttribute: true,
          usePathForSuiteName: true,
          // 自定义字段,CI 里直接通配符找图
          classNameTemplate: '{classname}',
          titleTemplate: '{title}',
          ancestorSeparator: ' › ',
          suiteNameTemplate: '{filepath}',
          // 关键:把截图目录作为 property 注入
          properties: {
            screenshotDir: '<rootDir>/test-results/screenshots'
          }
        }]
      ]
    };
    
  3. 在 .storybook/jest-setup.js 里捕获失败并截图

    import { configure } from '@storybook/test-runner';
    import { mkdirSync } from 'fs';
    import { join } from 'path';
    
    const screenshotDir = 'test-results/screenshots';
    mkdirSync(screenshotDir, { recursive: true });
    
    // 每个测试结束后运行
    afterEach(async () => {
      // test-runner 把 page 注入全局
      if (expect.getState().currentTestName && expect.getState().numFailedTests > 0) {
        const testName = expect.getState().currentTestName.replace(/[^a-zA-Z0-9]/g, '_');
        const path = join(screenshotDir, `${testName}.png`);
        await global.page.screenshot({ path, fullPage: true });
        // 把路径写进环境变量,供 jest-junit 读取
        process.env[`SCREENSHOT_${expect.getState().currentTestName}`] = path;
      }
    });
    
  4. 运行命令

    test-storybook --url http://127.0.0.1:6006 --config-dir .storybook --runner-config jest.config.storybook.js
    
  5. 结果

    • test-results/junit.xml 中每个失败的 <testcase> 会多出
      <properties>
        <property name="screenshot" value="/var/jenkins_home/workspace/xxx/test-results/screenshots_Button_Primary_play.png"/>
      </properties>
      
    • Jenkins 的 JUnit 插件可直接解析,“测试趋势图” 里红色失败条对应图片能被 HTML Publisher 插件归档,钉钉机器人 通过解析 XML 即可把截图链接推送到群里。

拓展思考

  1. 如果团队使用 Cypress 而不是 playwright,只需把 @storybook/test-runner 换成 storybook-cypress-runner,在 cypress/support/e2e.js 的 afterEach 里用 cy.screenshot(),并通过 cypress-junit-reporter 把截图路径写进同一套 junit.xml,思路完全一致。
  2. 对于 monorepo 场景,可在 jest-junit 里加 outputNameTemplate: '{suiteName}-junit.xml',让每个子包产出独立报告,Jenkins 的 pipeline 通配符 **/test-results/*junit.xml 即可一次性收集。
  3. 如果公司采用 Allure 而不是原生 JUnit,jest-allure 支持把截图作为附件上传,Allure 服务器 能更炫酷地展示失败步骤与图,但Allure 镜像在国内网络下需配置公司 Nexus 代理,面试时可作为“进阶方案”抛出。