vue3 vite 使用vitest 单元测试 组件测试

发布于:2025-08-07 ⋅ 阅读:(28) ⋅ 点赞:(0)

单元测试

pnpm add -D vitest vue-test-utils @vue/test-utils jsdom @testing-library/vue @testing-library/jest-dom @vitest/ui

ts项目需要加上
pnpm add -D @types/jest

修改 vite.config.ts

// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    globals: true,       // 支持 describe、it、expect 等全局函数
    environment: 'jsdom', // 模拟浏览器环境
    setupFiles: './test/setup.ts', // 可选,设置初始化文件
    include: ['tests/**/*.test.ts'],
  }
})

初始化测试文件结构

在项目根目录下创建 tests 目录:

📁 tests
│
├── 📄 setup.ts        // 初始化内容,比如 jest-dom 扩展
├── 📄 button.test.ts  // 单元测试示例
├── 📄 HelloWorld.test.ts  // 组件测试示例

  • tests/setup.ts 示例:
import '@testing-library/jest-dom'

、编写一个单元测试(函数测试)

  • src/utils/math.ts
export const add = (a: number, b: number) => a + b

tests/math.test.ts

import { describe, it, expect } from 'vitest'
import { add } from '../src/utils/math'

describe('math utils', () => {
  it('adds numbers correctly', () => {
    expect(add(1, 2)).toBe(3)
  })
})

编写一个组件测试(UI 组件

src/components/HelloWorld.vue

<template>
  <div>
    <p data-testid="msg">{{ msg }}</p>
    <button @click="count++">Count: {{ count }}</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>

tests/HelloWorld.test.ts

import { render, fireEvent } from '@testing-library/vue'
import HelloWorld from '../src/components/HelloWorld.vue'
import { describe, it, expect } from 'vitest'

describe('HelloWorld.vue', () => {
  it('renders props.msg', () => {
    const { getByTestId } = render(HelloWorld, { props: { msg: 'Hello Vitest' } })
    expect(getByTestId('msg')).toHaveTextContent('Hello Vitest')
  })

  it('increments counter on click', async () => {
    const { getByText } = render(HelloWorld, { props: { msg: 'Click test' } })
    const button = getByText(/Count:/)
    await fireEvent.click(button)
    expect(button.textContent).toBe('Count: 1')
  })
})

运行测试

pnpm vitest
# 或使用 UI 面板查看更方便
pnpm vitest --ui

测试类型 工具 用途 适用阶段
单元测试 Vitest 测试函数逻辑,如格式化、计算 编写完函数或逻辑模块后立刻写
组件测试 Vue Test Utils + Vitest 测试组件渲染/交互 写完一个组件后就写
集成测试 同上 组件之间配合 重要流程完成后写
E2E测试(端到端) Playwright / Cypress 模拟用户操作,整个页面测试 大功能开发完后统一写

测试用例目录

在这里插入图片描述

No test files found. You can change the file name pattern by pressing “p”

检查vite.config.ts的配置信息路径是否正确

vite.config.ts配置

test: {
    // jest like test api
    globals: true,
    // 模拟dom环境
    environment: 'happy-dom',
    include: [
    'src/tests/**/*.test.ts', //这里目录要正确不然会报错找不到测试脚本
    'src/tests/**/*.spec.ts',
  ],
    setupFiles: 'src/tests/setup.ts',
    // 支持tsx,jsx
    transformMode: {
      web: [/.[tj]sx$/]
    }
  },

package.json配置

 "test": "vitest"

运行命令pnpm test 即可执行


网站公告

今日签到

点亮在社区的每一天
去签到