全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-23 6 分钟 ✍️ juanwangdev

Vitest 单元测试框架

Vitest 是 Vite 生态的测试框架,配置简单、执行速度快。

Vitest 特点

特点说明
Vite 集成共享 Vite 配置
ESM 支持原生支持 ES 模块
速度快使用 Vite 转换
Jest 兼容API 类似 Jest

安装 Vitest

Bash
npm add -D vitest

配置 Vitest

JavaScript
// vite.config.js
export default defineConfig({
  test: {
    // Vitest 配置
    globals: true,
    environment: 'jsdom',
    coverage: {
      reporter: ['text', 'html']
    }
  }
})

注意:Vitest 配置集成在 vite.config.js 中。

编写测试

JavaScript
// sum.test.js
import { describe, it, expect } from 'vitest'
import { sum } from './sum'

describe('sum', () => {
  it('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3)
  })

  it('handles negative numbers', () => {
    expect(sum(-1, -2)).toBe(-3)
  })
})

运行测试

Bash
# 运行所有测试
vitest

# 运行单个文件
vitest sum.test.js

# 监听模式
vitest --watch

Vue 组件测试

JavaScript
import { mount } from '@vue/test-utils'
import Button from './Button.vue'

describe('Button', () => {
  it('renders text', () => {
    const wrapper = mount(Button, {
      props: { text: 'Click me' }
    })
    expect(wrapper.text()).toBe('Click me')
  })
})

测试环境配置

JavaScript
export default defineConfig({
  test: {
    environment: 'jsdom',  # DOM 环境
    setupFiles: ['./test/setup.js'],
    globals: true          # 全局 API
  }
})

覆盖率报告

Bash
vitest run --coverage

输出覆盖率:

YAML
Coverage report:
File      | Stmts | Branch | Funcs | Lines
sum.js    | 100%  | 100%   | 100%  | 100%

CI 集成

text
- name: Test
  run: vitest run

Vitest 与 Jest 对比

对比项VitestJest
配置共享 Vite独立配置
ESM原生支持需配置
速度中等
APIJest 兼容Jest 标准

要点总结

  • Vitest 与 Vite 共享配置
  • API 类似 Jest 易上手
  • 原生支持 ESM 模块
  • coverage 生成覆盖率报告

📝 发现内容有误?点击此处直接编辑

← 上一篇 Vitepress 文档站点
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库