vitest-testing by secondsky/claude-skills
npx skills add https://github.com/secondsky/claude-skills --skill vitest-testing使用 Vitest 测试 JavaScript/TypeScript 项目的专业知识 - 一个由 Vite 驱动的极速测试框架。
# 使用 Bun(推荐)
bun add -d vitest
# 使用 npm
npm install -D vitest
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node', // 或 'jsdom'
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
thresholds: { lines: 80, functions: 80, branches: 80 },
},
include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
})
# 运行所有测试(推荐使用 bun)
bun test
# 监视模式(默认)
bun test --watch
# 运行一次(CI 模式)
bun test --run
# 带覆盖率
bun test --coverage
# 特定文件
bun test src/utils/math.test.ts
# 模式匹配
bun test --grep="calculates sum"
# UI 模式(交互式)
bun test --ui
# 详细输出
bun test --reporter=verbose
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { add, subtract } from './math'
describe('数学工具', () => {
beforeEach(() => {
// 每个测试前的设置
})
it('正确相加两个数字', () => {
expect(add(2, 3)).toBe(5)
})
it('正确相减两个数字', () => {
expect(subtract(5, 3)).toBe(2)
})
})
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
describe.each([
{ input: 2, expected: 4 },
{ input: 3, expected: 9 },
])('平方函数', ({ input, expected }) => {
it(`将 ${input} 平方为 ${expected}`, () => {
expect(square(input)).toBe(expected)
})
})
// 相等性
expect(value).toBe(expected)
expect(value).toEqual(expected)
// 真值性
expect(value).toBeTruthy()
expect(value).toBeNull()
expect(value).toBeDefined()
// 数字
expect(number).toBeGreaterThan(3)
expect(number).toBeCloseTo(0.3, 1)
// 字符串/数组
expect(string).toMatch(/pattern/)
expect(array).toContain(item)
// 对象
expect(object).toHaveProperty('key')
expect(object).toMatchObject({ a: 1 })
// 异常
expect(() => throwError()).toThrow('message')
// Promise
await expect(promise).resolves.toBe(value)
await expect(promise).rejects.toThrow()
import { vi } from 'vitest'
const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue('async result')
mockFn.mockImplementation((x) => x * 2)
expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg')
vi.mock('./api', () => ({
fetchUser: vi.fn(() => ({ id: 1, name: '测试用户' })),
}))
import { fetchUser } from './api'
beforeEach(() => {
vi.clearAllMocks()
})
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.restoreAllMocks())
it('推进定时器', () => {
const callback = vi.fn()
setTimeout(callback, 1000)
vi.advanceTimersByTime(1000)
expect(callback).toHaveBeenCalledOnce()
})
it('模拟日期', () => {
const date = new Date('2024-01-01')
vi.setSystemTime(date)
expect(Date.now()).toBe(date.getTime())
})
# 生成覆盖率报告
bun test --coverage
# HTML 报告
bun test --coverage --coverage.reporter=html
open coverage/index.html
# 检查阈值
bun test --coverage --coverage.thresholds.lines=90
import request from 'supertest'
import { app } from './app'
describe('API 端点', () => {
it('创建用户', async () => {
const response = await request(app)
.post('/api/users')
.send({ name: 'John' })
.expect(201)
expect(response.body).toMatchObject({
id: expect.any(Number),
name: 'John',
})
})
})
math.ts → math.test.tsdescribe() 块分组相关测试concurrent 测试beforeAll() 共享昂贵的固定装置test-quality-analysis - 检测测试异味playwright-testing - E2E 测试mutation-testing - 验证测试有效性每周安装次数
121
仓库
GitHub 星标数
91
首次出现
2026年1月25日
安全审计
已安装于
claude-code105
opencode101
gemini-cli100
codex99
cursor98
github-copilot97
Expert knowledge for testing JavaScript/TypeScript projects using Vitest - a blazingly fast testing framework powered by Vite.
# Using Bun (recommended)
bun add -d vitest
# Using npm
npm install -D vitest
// vitest.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node', // or 'jsdom'
coverage: {
provider: 'v8',
reporter: ['text', 'json', 'html'],
thresholds: { lines: 80, functions: 80, branches: 80 },
},
include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
},
})
# Run all tests (prefer bun)
bun test
# Watch mode (default)
bun test --watch
# Run once (CI mode)
bun test --run
# With coverage
bun test --coverage
# Specific file
bun test src/utils/math.test.ts
# Pattern matching
bun test --grep="calculates sum"
# UI mode (interactive)
bun test --ui
# Verbose output
bun test --reporter=verbose
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { add, subtract } from './math'
describe('Math utilities', () => {
beforeEach(() => {
// Setup before each test
})
it('adds two numbers correctly', () => {
expect(add(2, 3)).toBe(5)
})
it('subtracts two numbers correctly', () => {
expect(subtract(5, 3)).toBe(2)
})
})
describe.each([
{ input: 2, expected: 4 },
{ input: 3, expected: 9 },
])('square function', ({ input, expected }) => {
it(`squares ${input} to ${expected}`, () => {
expect(square(input)).toBe(expected)
})
})
// Equality
expect(value).toBe(expected)
expect(value).toEqual(expected)
// Truthiness
expect(value).toBeTruthy()
expect(value).toBeNull()
expect(value).toBeDefined()
// Numbers
expect(number).toBeGreaterThan(3)
expect(number).toBeCloseTo(0.3, 1)
// Strings/Arrays
expect(string).toMatch(/pattern/)
expect(array).toContain(item)
// Objects
expect(object).toHaveProperty('key')
expect(object).toMatchObject({ a: 1 })
// Exceptions
expect(() => throwError()).toThrow('message')
// Promises
await expect(promise).resolves.toBe(value)
await expect(promise).rejects.toThrow()
import { vi } from 'vitest'
const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue('async result')
mockFn.mockImplementation((x) => x * 2)
expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg')
vi.mock('./api', () => ({
fetchUser: vi.fn(() => ({ id: 1, name: 'Test User' })),
}))
import { fetchUser } from './api'
beforeEach(() => {
vi.clearAllMocks()
})
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.restoreAllMocks())
it('advances timers', () => {
const callback = vi.fn()
setTimeout(callback, 1000)
vi.advanceTimersByTime(1000)
expect(callback).toHaveBeenCalledOnce()
})
it('mocks dates', () => {
const date = new Date('2024-01-01')
vi.setSystemTime(date)
expect(Date.now()).toBe(date.getTime())
})
# Generate coverage report
bun test --coverage
# HTML report
bun test --coverage --coverage.reporter=html
open coverage/index.html
# Check against thresholds
bun test --coverage --coverage.thresholds.lines=90
import request from 'supertest'
import { app } from './app'
describe('API endpoints', () => {
it('creates a user', async () => {
const response = await request(app)
.post('/api/users')
.send({ name: 'John' })
.expect(201)
expect(response.body).toMatchObject({
id: expect.any(Number),
name: 'John',
})
})
})
math.ts → math.test.tsdescribe() blocksconcurrent tests for independent async testsbeforeAll()test-quality-analysis - Detecting test smellsplaywright-testing - E2E testingmutation-testing - Validate test effectivenessWeekly Installs
121
Repository
GitHub Stars
91
First Seen
Jan 25, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
claude-code105
opencode101
gemini-cli100
codex99
cursor98
github-copilot97
Vue 3 调试指南:解决响应式、计算属性与监听器常见错误
11,900 周安装
阿里云KMS密钥管理服务自动化脚本 - 安全云服务API调用指南
267 周安装
阿里云Model Studio模型爬取与技能自动生成工具 - 自动化AI技能开发
267 周安装
金融市场分析智能体:AI驱动股票分析、投资评级与数据自动化工具
278 周安装
Effect-TS 专家指南:TypeScript 函数式编程库,掌握结构化并发与错误处理
269 周安装
阿里云Model Studio文本嵌入技能:text-embedding-v4/v3/v2/v1与qwen3模型快速上手
72 周安装
阿里云AIContent管理技能:OpenAPI调用、SDK使用与AI内容资源管理指南
268 周安装