vue3-element-admin单元测试:组件测试与集成测试
·
vue3-element-admin单元测试:组件测试与集成测试
测试环境搭建
在进行单元测试前,需先搭建测试环境。通过npm安装Vitest测试框架、Vue测试工具及DOM模拟环境:
npm install vitest @vue/test-utils happy-dom -D
安装成功后,测试相关依赖将被添加到package.json的devDependencies中。
组件测试实践
基础组件测试示例
以项目中的src/components/Button/Button.vue组件为例,创建测试文件Button.test.ts:
import { describe, it, expect } from 'vitest'
import { mount } from '@vue/test-utils'
import Button from '../src/components/Button/Button.vue'
describe('Button.vue', () => {
it('renders button text correctly', () => {
const wrapper = mount(Button, {
props: {
label: '测试按钮'
}
})
expect(wrapper.text()).toContain('测试按钮')
})
it('applies correct type class', () => {
const wrapper = mount(Button, {
props: {
type: 'primary',
label: '主要按钮'
}
})
expect(wrapper.classes()).toContain('el-button--primary')
})
})
表单组件测试
以src/components/Form/Input.vue组件为例,测试表单输入功能:
import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import Input from '../src/components/Form/Input.vue'
describe('Input.vue', () => {
it('emits input event on value change', async () => {
const wrapper = mount(Input)
const input = wrapper.find('input')
await input.setValue('测试输入')
expect(wrapper.emitted('input')).toHaveLength(1)
expect(wrapper.emitted('input')![0]).toEqual(['测试输入'])
})
it('displays placeholder correctly', () => {
const wrapper = mount(Input, {
props: {
placeholder: '请输入内容'
}
})
expect(wrapper.find('input').attributes('placeholder')).toBe('请输入内容')
})
})
集成测试场景
页面组件测试
以src/views/login/Login.vue登录页面为例,测试用户登录流程:
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { mount } from '@vue/test-utils'
import { createTestingPinia } from '@pinia/testing'
import Login from '../src/views/login/Login.vue'
import { useUserStore } from '../src/store/modules/user-store.ts'
describe('Login.vue', () => {
beforeEach(() => {
// 模拟Pinia状态管理
const pinia = createTestingPinia({
initialState: {
user: {
token: '',
userInfo: null
}
}
})
// 模拟路由跳转
vi.mock('vue-router', () => ({
useRouter: () => ({
push: vi.fn()
})
}))
})
it('should login successfully with correct credentials', async () => {
const wrapper = mount(Login, {
global: {
plugins: [pinia]
}
})
const userStore = useUserStore()
userStore.login = vi.fn().mockResolvedValue({ token: 'test-token' })
// 输入用户名密码
await wrapper.find('input[name="username"]').setValue('admin')
await wrapper.find('input[name="password"]').setValue('123456')
// 点击登录按钮
await wrapper.find('button[type="submit"]').trigger('click')
// 验证登录方法被调用
expect(userStore.login).toHaveBeenCalledWith({
username: 'admin',
password: '123456'
})
})
})
API交互测试
测试src/api/user-api.ts中的用户相关API调用:
import { describe, it, expect, vi } from 'vitest'
import axios from 'axios'
import { getUserInfo } from '../src/api/user-api.ts'
// 模拟axios
vi.mock('axios')
const mockedAxios = vi.mocked(axios)
describe('user-api.ts', () => {
it('getUserInfo should return user data', async () => {
const mockUser = { id: 1, name: 'Test User' }
mockedAxios.get.mockResolvedValue({ data: { code: 200, data: mockUser } })
const result = await getUserInfo(1)
expect(result).toEqual(mockUser)
expect(mockedAxios.get).toHaveBeenCalledWith('/api/user/1')
})
})
测试配置与运行
配置Vitest
在项目根目录创建vite.config.test.ts配置文件:
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
environment: 'happy-dom',
include: ['**/*.test.ts'],
exclude: ['node_modules'],
coverage: {
reporter: ['text', 'json', 'html']
}
}
})
添加测试脚本
在package.json中添加测试脚本:
"scripts": {
"test": "vitest",
"test:watch": "vitest --watch",
"test:coverage": "vitest run --coverage"
}
运行测试命令:
# 执行所有测试
npm test
# 查看测试覆盖率
npm run test:coverage
测试目录结构
推荐的测试文件目录结构与源码保持一致,便于维护:
src/
├── components/
│ ├── Button/
│ │ ├── Button.vue
│ │ └── Button.test.ts
├── views/
│ ├── login/
│ │ ├── Login.vue
│ │ └── Login.test.ts
├── api/
│ ├── user-api.ts
│ └── user-api.test.ts
测试最佳实践
- 组件隔离:使用
shallowMount隔离组件,只测试当前组件逻辑 - 模拟外部依赖:对API调用、路由跳转等外部依赖进行模拟
- 聚焦用户行为:通过触发DOM事件模拟用户操作,而非直接调用方法
- 编写有意义的断言:验证组件状态变化或副作用,而非实现细节
- 持续集成:在CI流程中添加测试步骤,确保代码质量
通过单元测试与集成测试相结合的方式,可以有效保障vue3-element-admin项目的代码质量,减少回归错误,提高开发效率。
更多推荐



所有评论(0)