| name | vitest-testing |
| description | Vitest testing framework patterns and best practices. Use when writing unit tests, integration tests, configuring vitest.config, mocking with vi.mock/vi.fn, using snapshots, or setting up test coverage. Triggers on describe, it, expect, vi.mock, vi.fn, beforeEach, afterEach, vitest. |
Vitest Best Practices
Quick Reference
import { describe, it, expect, beforeEach, vi } from 'vitest'
describe('feature name', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('should do something specific', () => {
expect(actual).toBe(expected)
})
it.todo('planned test')
it.skip('temporarily disabled')
it.only('run only this during dev')
})
Common Assertions
expect(value).toBe(42)
expect(obj).toEqual({ a: 1 })
expect(obj).toStrictEqual({ a: 1 })
expect(value).toBeTruthy()
expect(value).toBeFalsy()
expect(value).toBeNull()
expect(value).toBeUndefined()
expect(0.1 + 0.2).toBeCloseTo(0.3)
expect(value).toBeGreaterThan(5)
expect(str).toMatch(/pattern/)
expect(str).toContain('substring')
expect(array).toContain(item)
expect(array).toHaveLength(3)
expect(obj).toHaveProperty('key')
expect(obj).toHaveProperty('nested.key', 'value')
expect(obj).toMatchObject({ subset: 'of properties' })
expect(() => fn()).toThrow()
expect(() => fn()).toThrow('error message')
expect(() => fn()).toThrow(/pattern/)
Async Testing
it('fetches data', async () => {
const data = await fetchData()
expect(data).toEqual({ id: 1 })
})
await expect(fetchData()).resolves.toEqual({ id: 1 })
await expect(fetchData()).rejects.toThrow('Error')
expect(promise).resolves.toBe(value)
Quick Mock Reference
const mockFn = vi.fn()
mockFn.mockReturnValue(42)
mockFn.mockResolvedValue({ data: 'value' })
expect(mockFn).toHaveBeenCalled()
expect(mockFn).toHaveBeenCalledWith('arg1', 'arg2')
expect(mockFn).toHaveBeenCalledTimes(2)
Verification gates
Use this sequence when you add or change tests; each step has an objective pass condition.
- Run the test suite — From the package or workspace root, run the same command CI uses (check
package.json scripts; often vitest run, pnpm test, or npm test). Pass: exit code is 0 and the report shows zero failing tests.
- Async matchers — Pass: every
expect(…).resolves and expect(…).rejects is prefixed with await (await expect(...)), as in Async Testing. A line where resolves or rejects appears without await fails this gate.
Additional Documentation
Test Methods Quick Reference
| Method | Purpose |
|---|
it() / test() | Define test |
describe() | Group tests |
beforeEach() / afterEach() | Per-test hooks |
beforeAll() / afterAll() | Per-suite hooks |
.skip | Skip test/suite |
.only | Run only this |
.todo | Placeholder |
.concurrent | Parallel execution |
.each([...]) | Parameterized tests |