如何为自定义组件编写stories并自动截图对比?

解读

在国内一线互联网与金融科技公司的 Dash 交付流程中,自定义 React 组件(如 3D 地球、甘特图、低代码表单)一旦上线,回归测试全靠人眼盯屏,极易出现“像素级”偏差。面试官抛出此题,想验证三件事:

  1. 你是否理解 Dash 组件本质是 React 组件,必须走前端工程化链路;
  2. 你是否能把“写 Storybook 故事”与“自动截图比对”无缝接进 Python 主导的 CI(GitLab-CI、Jenkins、阿里云效);
  3. 你是否能在不泄露业务数据的前提下,给出可落地的中国本土化方案(镜像源、字体、License)。

知识点

  1. Dash 组件编译链:dash-generator 把 React propTypes 转成 Python 类,生成 dash-xxx-components 包。
  2. Storybook 6/7 的 Component Story Format 3(CSF3),以及 @storybook/addon-interactions 用于声明交互步骤。
  3. 像素级回归工具:chromatic(SaaS,国内需科学上网)、@storybook/test-runner + jest-image-snapshot(本地化,无翻墙成本)。
  4. GitLab-CI 的 parallel matrix 与缓存策略,解决“npm install 龟速”问题(淘宝源 + 自建 Nexus)。
  5. 字体一致性:指定 "PingFang SC" 为默认 sans-serif,避免 macOS 与 Linux 截图差 2px。
  6. 数据脱敏:使用 faker.js 生成假数据,防止截图里出现真实客户名称。
  7. 阈值调优:jest-image-snapshot 的 threshold 建议 0.2(单核 CI 1920×1080 环境实测),既防误报又不过度宽松。

答案

步骤一:组件脚手架

npx dash-component-generator my-comp
cd my-comp
npm i -D react react-dom @storybook/react @storybook/test-runner jest-image-snapshot

步骤二:编写 CSF3 故事

// src/stories/MyComp.stories.js
import MyComp from '../lib/components/MyComp.react';

export default {
  component: MyComp,
  title: 'DataDisplay/MyComp',
};

export const Primary = {
  args: {
    data: Array.from({length: 5}, (_, i) => ({x: i, y: i * i})),
    color: '#0052d9',   // 腾讯蓝,符合国内审美
  },
};

步骤三:注册交互并截图

// src/stories/MyComp.interaction.js
import { within, userEvent } from '@storybook/testing-library';

export const HoverState = {
  ...Primary,
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    await userEvent.hover(canvas.getByRole('button'));
  },
};

步骤四:本地截图比对脚本

// .storybook/test-runner.js
const { toMatchImageSnapshot } = require('jest-image-snapshot');
expect.extend({ toMatchImageSnapshot });

module.exports = {
  async postRender(page, context) {
    const image = await page.screenshot({ fullPage: true });
    expect(image).toMatchImageSnapshot({
      threshold: 0.2,
      customSnapshotsDir: `__snapshots__/${context.id}`,
    });
  },
};

步骤五:CI 集成(GitLab-CI 示例,国内加速)

image: registry.cn-hangzhou.aliyuncs.com/acs/nodejs:16

variables:
  FONTCONFIG_FILE: /etc/fonts/fonts.conf

cache:
  key: ${CI_COMMIT_REF_SLUG}
  paths:
    - node_modules/

before_script:
  - npm config set registry https://registry.npmmirror.com
  - npm ci

test:visual:
  stage: test
  script:
    - npm run build-storybook --quiet
    - npx concurrently -k -s first -n "SB,TEST" -c "magenta,blue"
        "npx http-server storybook-static -p 6006 --silent"
        "npx wait-on tcp:6006 && npm run test-storybook"
  artifacts:
    when: always
    paths:
      - __snapshots__/__diff_output__/
    expire_in: 3 days

步骤六:Python 侧一键调用

# dash_app/check_visual.py
import subprocess, sys, pathlib

def test_stories():
    root = pathlib.Path(__file__).parent / "my-comp"
    subprocess.run(["npm", "run", "test-storybook"], cwd=root, check=True)

if __name__ == "__main__":
    test_stories()

执行 python check_visual.py,若出现 diff 图片,CI 自动失败并上传 diff 报告到 GitLab MR,实现“纯 Python 命令”驱动前端像素级回归。

拓展思考

  1. 大组件首次加载 200+ DOM 节点,截图易超时:可在 CI 里把 page.setDefaultTimeout(10000) 调高,并对组件做 React.lazy 分包,减少首屏节点。
  2. 多主题(暗黑模式)回归:利用 Storybook 的 globalTypes 定义 theme 工具栏,一条 story 自动生成 light/dark 两份截图,阈值单独设 0.15,避免深色抗锯齿差异。
  3. 国内私企对 SaaS 出境数据敏感,若无法用 chromatic,可把 jest-image-snapshot 换成 pixelmatch 自研服务,接入 MinIO 做快照存储,完全内网闭环。
  4. 与 Dash 官方 dash.testing 桥接:在 pytest 夹具里先起 dash_duo.server,再用 selenium 对整页截图,与 Storybook 组件级截图互补,实现“组件 + 集成”双保险。
  5. 未来若组件库升级 React 18,CI 需同步切到 storybook@7 并要求 react@18,否则 createRoot API 差异会导致截图整体偏移 1px,需全量重新 baseline。