如何为组件库使用 Cypress Component Testing
解读
国内中大型团队自研 React 组件库已成标配,面试时面试官想确认两点:
- 你是否理解“组件级测试”与“端到端测试”的差异;
- 你是否能把 Cypress 10+ 的 Component Test Runner 无缝接入 monorepo、Vite/Webpack、TypeScript、CSS-in-JS 等国内真实工程链。
回答要体现“配置—编写—调试—CI”闭环,并给出可落地的脚本、命令、目录规范,避免只贴官方文档。
知识点
- Cypress 10 之后内置 component testing,与 e2e 共用同一套驱动,但使用 mount 而非 cy.visit
- 国内主流组件库基于 Vite + TypeScript + React 18,需安装 cypress、@cypress/react、@cypress/vite-dev-server
- 支持 Hooks、React Router、Redux、Portals、微前端等场景,但需手动 mock 全局样式、i18n、主题 token
- 在 CI 侧,国内公司普遍使用 GitLab-CI 或 GitHub Actions,需配合 --component、--record、并行化、缓存 ~/.cache/Cypress
- 与 Storybook 互补:Storybook 做视觉与文档,Cypress 做交互与回归,二者可复用 stories 文件
- 覆盖率:借助 @cypress/code-coverage + babel-plugin-istanbul,可在流水线生成 lcov 上报至 SonarQube 或阿里云效
答案
(以下以 Vite + pnpm monorepo 为例,步骤可直接搬进面试现场白板)
-
安装
pnpm add -D cypress @cypress/react @cypress/vite-dev-server @cypress/code-coverage -
初始化
npx cypress open --component
选择“React”、“Vite”,自动生成 cypress.config.ts 与 cypress/support/component.ts -
配置 cypress.config.ts
import { defineConfig } from 'cypress'
import { devServer } from '@cypress/vite-dev-server'
export default defineConfig({
component: {
devServer(devServerConfig) {
return devServer({
...devServerConfig,
viteConfig: {
configFile: './vite.config.ts',
css: { modules: { localsConvention: 'camelCase' } }
}
})
},
specPattern: 'src/**/*.cy.{ts,tsx}',
supportFile: 'cypress/support/component.ts'
}
}) -
全局样式与主题注入
// cypress/support/component.ts
import '../../src/styles/index.less'
import { ThemeProvider } from '@company/design-tokens'
import { mount } from '@cypress/react'
Cypress.Commands.add('mount', (jsx, options = {}) => {
const wrapped = <ThemeProvider>{jsx}</ThemeProvider>
return mount(wrapped, options)
})
declare global { namespace Cypress { interface Chainable { mount: typeof mount } } } -
编写测试
src/Button/Button.cy.tsx
import { Button } from './index'
it('支持尺寸与点击事件', () => {
cy.mount(<Button size="large" onClick={cy.spy().as('click')}>提交</Button>)
cy.get('button').should('have.class', 'btn-large').and('have.text', '提交')
cy.get('button').click()
cy.get('@click').should('have.been.calledOnce')
}) -
命令与脚本
package.json
"scripts": {
"test:ct": "cypress run --component",
"test:ct-open": "cypress open --component",
"test:ct-coverage": "cypress run --component --env coverage=true"
} -
GitLab-CI 片段
test_component:
stage: test
image: cypress/included:12.14.0
cache:
key: cypress-cache
paths: [ ~/.cache/Cypress ]
script:- pnpm install --frozen-lockfile
- pnpm test:ct --record --parallel --tag component
coverage: '/Lines\s*:\s*(\d+.\d+)%/'
artifacts:
reports:
coverage_report:
coverage_format: lcov
path: coverage/lcov.info
-
常见坑
- CSS Modules 找不到类名:在 vite.config.ts 里开启 localsConvention 并在测试里用 data-cy 做断言锚点
- Portal/下拉定位:使用 cypress-real-events 插件,或把 attachTo 设为 document.body
- 国际化:在 cy.mount 里包一层 I18nProvider,默认 lang='zh-CN'
- 版本锁定:国内镜像建议同步淘宝 npm 与 Cypress 下载镜像,防止 CI 拉包超时
拓展思考
-
如何与视觉回归结合?
可接入 cypress-image-diff-js,在 CI 中把快照上传到阿里云 OSS,配合公司自研的“像素眼”平台做 diff 审批流。 -
如何复用 Storybook stories?
使用 @storybook/testing-react 把 story 直接转成 Cypress 测试,减少用例重复;但需注意 story 里若依赖 storybook 专属参数(如 msw 装饰器)要在 Cypress 里再 mock 一次。 -
如何测试多主题与暗黑模式?
在测试用例里动态切换 CSS 变量或主题 Provider,通过 cy.get('html').should('have.class', 'dark') 断言,结合 cypress-each 做矩阵测试。 -
如何与单元测试互补?
组件库仍需 vitest/jest + @testing-library/react 做纯逻辑快照,Cypress 专注交互与样式;二者覆盖率合并上报,让面试官看到你对“测试金字塔”有落地思考。