Vue组件测试
info
学习内容
- 如何在Vue中设置组件测试
- 如何为Vue项目配置Cypress
框架支持
Cypress组件测试支持以下框架的Vue 3+:
教程
访问入门指南,获取将组件测试添加到项目的分步教程,并学习如何编写第一个测试。
安装
要在Vue中开始使用Cypress组件测试,请将Cypress安装到项目中:
- npm
- yarn
- pnpm
npm install cypress --save-dev
yarn add cypress --dev
pnpm add --save-dev cypress
打开Cypress:
- npm
- yarn
- pnpm
npx cypress open
yarn cypress open
pnpm cypress open

选择组件测试
Cypress启动器将引导您完成项目配置。
框架配置
Cypress组件测试开箱即用支持Vite和自定义Webpack配置。Cypress在设置过程中会自动检测这些框架并进行正确配置。以下示例仅供参考。
Vue与Vite
Cypress组件测试支持使用Vite 4+作为打包工具的Vue应用。
Vite配置
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
component: {
devServer: {
framework: 'vue',
bundler: 'vite',
},
},
})
import { defineConfig } from 'cypress'
export default defineConfig({
component: {
devServer: {
framework: 'vue',
bundler: 'vite',
},
},
})
Vue Vite示例应用
Vue与Webpack
Cypress组件测试支持使用Webpack 4+作为打包工具的Vue应用。
Webpack配置
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
const webpackConfig = require('./webpack.config')
module.exports = defineConfig({
component: {
devServer: {
framework: 'vue',
bundler: 'webpack',
// 可选传入webpack配置
webpackConfig,
webpackConfig: async () => {
// ...处理逻辑...
const modifiedConfig = await injectCustomConfig(baseConfig)
return modifiedConfig
},
},
},
})
import { defineConfig } from 'cypress'
import webpackConfig from './webpack.config'
export default defineConfig({
component: {
devServer: {
framework: 'vue',
bundler: 'webpack',
// 可选传入webpack配置
webpackConfig,
webpackConfig: async () => {
// ...处理逻辑...
const modifiedConfig = await injectCustomConfig(baseConfig)
return modifiedConfig
},
},
},
})
如果不提供配置,Cypress会尝试推断您的webpack配置。如果Cypress无法推断或您希望对配置进行修改,可以通过webpackConfig
选项手动传入。