如何为 script setup 语法编写 Cypress 组件测试?

解读

在国内 Vue3 项目里,<script setup> 已成为默认写法,面试官问“怎么给这种语法写 Cypress 组件测试”,核心想确认三件事:

  1. 你是否真的把 Cypress 当成“组件级测试框架”来用,而不是只会端到端;
  2. 能否把 Vite/Webpack 的 dev-server 与 Cypress 的 mount API 串起来;
  3. 是否理解 <script setup> 编译后的“自动暴露”特性,从而正确传 props、插槽与事件。

答不到“mount 参数怎么写”“Vite 配置怎么改”这两个细节,基本会被判“只看过文档,没动手”。

知识点

  • Cypress 10+ 的 Component Testing 模式与 mount API
  • cypress.config.ts 里 devServer 配置项(vite/webpack)
  • <script setup> 编译后 自动暴露 的 setup 上下文,无需额外 defineExpose
  • 使用 @cypress/vue 或 @cypress/vite-dev-server 插件
  • data-cy 选择器与 cy.mount 自定义命令的封装
  • 在测试里 动态改 props 触发响应式更新
  • 利用 cy.spy 对 emit 事件做断言
  • 国内常见 CI(GitLab-CI、Jenkins、GitHub Actions)里 component + e2e 并行跑的最佳实践

答案

  1. 安装依赖(以 Vite 为例)
npm i -D cypress @cypress/vite-dev-server @vue/test-utils
  1. 改造 cypress.config.ts
import { defineConfig } from 'cypress'
import viteConfig from './vite.config'

export default defineConfig({
  component: {
    devServer: {
      framework: 'vue',
      bundler: 'vite',
      viteConfig
    },
    specPattern: 'src/**/*.cy.{js,ts,tsx}'
  }
})
  1. 在 cypress/support/component.ts 注册全局命令
import { mount } from '@cypress/vue'
declare global {
  namespace Cypress {
    interface Chainable {
      mount: typeof mount
    }
  }
}
Cypress.Commands.add('mount', mount)
  1. 被测组件 src/components/PriceCard.vue
<script setup lang="ts">
defineProps<{
  price: number
}>()
const emit = defineEmits<{
  buy: [count: number]
}>()
</script>

<template>
  <div data-cy="price">{{ price }}</div>
  <button data-cy="buy" @click="emit('buy', 1)">购买</button>
</template>
  1. 测试文件 src/components/PriceCard.cy.ts
import PriceCard from './PriceCard.vue'

it('响应式更新价格并触发购买事件', () => {
  const onBuy = cy.spy().as('onBuy')
  cy.mount(PriceCard, {
    props: {
      price: 100
    },
    attrs: {
      onBuy
    }
  })

  cy.get('[data-cy=price]').should('have.text', '100')

  // 动态改 props
  cy.mount(PriceCard, {
    props: {
      price: 200
    },
    attrs: {
      onBuy
    }
  })
  cy.get('[data-cy=price]').should('have.text', '200')

  cy.get('[data-cy=buy]').click()
  cy.get('@onBuy').should('have.been.calledWith', 1)
})
  1. 本地运行
npx cypress open --component

CI 中并行:

npx cypress run --component --record --parallel --tag component

拓展思考

  • 如果组件内部用 useRouter 或 Pinia,需要在 cy.mount 里统一注入 global.plugins,否则会出现 “router is undefined” 导致测试失败。
  • 对 Ant Design Vue 这类“懒加载样式”的库,要在 cypress/support/component.ts 里 import 'ant-design-vue/dist/antd.css',否则 CI 里会样式错乱。
  • 当项目同时存在 Vue2 遗留组件 与 Vue3 <script setup> 时,可通过 conditional mount 把 @cypress/vue2 与 @cypress/vue 分别注册到不同 specPattern,实现“一套框架,两种语法”共存。
  • 国内网络下,首次 cypress install 容易失败,可提前在 Dockerfile 里把 CYPRESS_INSTALL_BINARY=https://npmmirror.com/... 指向淘宝镜像,保证构建稳定。
  • 面试官常追问:“组件测试覆盖率怎么算?” 正确姿势是把 nyc 与 vite-plugin-istanbul 打通,在 cypress.config.ts 里打开 coverage: true,跑完后把 coverage/lcov.info 推送到 SonarQube 或 阿里云效,实现“代码质量门禁”。