测试工具链配置
测试工具链配置
Vite.js 的测试工具链配置直接影响开发效率和代码质量。合理的配置能让单元测试、组件测试和端到端测试无缝集成到开发流程中。
单元测试配置
Jest 是常见的单元测试框架。在 Vite 项目中安装相关依赖:
npm install --save-dev jest @types/jest @vue/test-utils
创建 jest.config.js
文件:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1'
},
transform: {
'^.+\\.vue$': '@vue/vue3-jest',
'^.+\\.ts$': 'ts-jest'
}
}
示例测试文件 src/utils/math.test.ts
:
import { add } from '@/utils/math'
describe('math utilities', () => {
it('adds two numbers correctly', () => {
expect(add(2, 3)).toBe(5)
})
})
组件测试配置
对于 Vue 组件测试,需要额外配置:
npm install --save-dev @testing-library/vue
配置 vite.config.js
支持测试:
export default defineConfig({
test: {
globals: true,
environment: 'jsdom'
}
})
组件测试示例 src/components/Button.test.ts
:
import { render } from '@testing-library/vue'
import Button from './Button.vue'
test('renders button with correct text', () => {
const { getByText } = render(Button, {
props: {
label: 'Click me'
}
})
expect(getByText('Click me')).toBeInTheDocument()
})
端到端测试配置
Cypress 适合做端到端测试。安装命令:
npm install --save-dev cypress
创建 cypress.config.js
:
const { defineConfig } = require('cypress')
module.exports = defineConfig({
e2e: {
baseUrl: 'http://localhost:5173',
setupNodeEvents(on, config) {
// 实现插件
}
}
})
测试示例 cypress/e2e/home.cy.js
:
describe('Home Page', () => {
it('successfully loads', () => {
cy.visit('/')
cy.contains('Welcome to Vite App').should('be.visible')
})
})
测试覆盖率配置
在 jest.config.js
中添加覆盖率配置:
module.exports = {
collectCoverage: true,
coverageDirectory: 'coverage',
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
}
测试环境变量处理
创建 .env.test
文件:
VITE_API_BASE=http://test.api.example.com
修改 vite.config.js
:
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
define: {
'process.env': env
}
}
})
测试与构建集成
在 package.json
中添加脚本:
{
"scripts": {
"test:unit": "jest",
"test:e2e": "cypress run",
"test": "run-p test:unit test:e2e"
}
}
测试工具链优化
使用 vite-plugin-test
插件优化测试体验:
import test from 'vite-plugin-test'
export default defineConfig({
plugins: [
test({
include: ['**/*.{test,spec}.{js,ts}'],
globals: true
})
]
})
测试数据模拟
创建 mock 服务:
// src/mocks/handlers.js
import { rest } from 'msw'
export const handlers = [
rest.get('/api/user', (req, res, ctx) => {
return res(
ctx.json({
id: 1,
name: 'Test User'
})
)
})
]
配置测试环境使用 mock:
// src/setupTests.js
import { setupServer } from 'msw/node'
import { handlers } from './mocks/handlers'
const server = setupServer(...handlers)
beforeAll(() => server.listen())
afterEach(() => server.resetHandlers())
afterAll(() => server.close())
测试类型检查
在 tsconfig.json
中添加测试类型支持:
{
"compilerOptions": {
"types": ["jest", "node"]
}
}
测试性能优化
并行执行测试:
// jest.config.js
module.exports = {
maxWorkers: '50%',
testEnvironment: 'jsdom'
}
对于大型测试套件,可以使用 jest-runner-groups
:
{
"scripts": {
"test:unit:fast": "jest --group=fast",
"test:unit:slow": "jest --group=slow"
}
}
测试报告生成
配置 Jest 生成 HTML 报告:
module.exports = {
reporters: [
'default',
['jest-html-reporters', {
publicPath: './test-reports',
filename: 'report.html'
}]
]
}
Cypress 报告配置:
// cypress.config.js
module.exports = defineConfig({
reporter: 'junit',
reporterOptions: {
mochaFile: 'cypress/results/output.xml'
}
})
测试与 CI/CD 集成
GitHub Actions 配置示例 .github/workflows/test.yml
:
name: Test
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: 16
- run: npm ci
- run: npm run test:unit
- run: npm run test:e2e
测试调试配置
VS Code 调试配置 .vscode/launch.json
:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Jest Tests",
"program": "${workspaceFolder}/node_modules/jest/bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen"
}
]
}
测试快照管理
Jest 快照测试示例:
import { render } from '@testing-library/vue'
import Component from './Component.vue'
test('renders correctly', () => {
const { container } = render(Component)
expect(container).toMatchSnapshot()
})
更新快照的命令:
npm test -- -u
测试工具链扩展
集成 Storybook 测试:
npx storybook init
配置 Storybook 测试插件 .storybook/main.js
:
module.exports = {
stories: ['../src/**/*.stories.@(js|ts)'],
addons: [
'@storybook/addon-actions',
'@storybook/addon-interactions'
],
framework: '@storybook/vue3'
}
测试与状态管理
测试 Pinia store 的示例:
import { setActivePinia, createPinia } from 'pinia'
import { useCounterStore } from '@/stores/counter'
describe('Counter Store', () => {
beforeEach(() => {
setActivePinia(createPinia())
})
it('increments count', () => {
const counter = useCounterStore()
counter.increment()
expect(counter.count).toBe(1)
})
})
测试路由
测试 Vue Router 的示例:
import { mount } from '@vue/test-utils'
import { createRouter, createWebHistory } from 'vue-router'
import Component from './Component.vue'
const router = createRouter({
history: createWebHistory(),
routes: [{ path: '/', component: Component }]
})
test('navigates to home', async () => {
const wrapper = mount(Component, {
global: {
plugins: [router]
}
})
await wrapper.find('a').trigger('click')
expect(wrapper.vm.$route.path).toBe('/')
})
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:复杂状态管理集成