Vitest Patterns
Skill Profile
(Select at least one profile to enable specific modules)
Overview
Vitest is a modern testing framework designed for the Vite ecosystem, but works with any project. It's 10-20x faster than Jest, with native TypeScript/ESM support and Jest-compatible API, making migration easy. This skill covers Vitest setup, basic testing, mocking, React component testing, async testing, snapshot testing, test utilities, and running tests.
Why This Matters
Vitest provides:
- Speed: 10-20x faster than Jest (Vite's transform pipeline)
- Native ESM/TypeScript: No transpilation config needed
- Jest Compatible: Same API, easy migration
- Watch Mode: Instant feedback with smart re-runs
- UI Mode: Visual test debugging interface
Core Concepts
- Configuration: Vite config integration
- Test Environment: jsdom, node, happy-dom
- Globals: describe, it, expect globally available
- Mocking: vi.fn(), vi.mock(), vi.spyOn()
- Snapshots: Snapshot testing for UI components
- Coverage: Built-in coverage with v8 or istanbul
- Watch Mode: Smart file watching and re-running
Inputs / Outputs / Contracts
- Inputs:
- <e.g., env vars, request payload, file paths, schema>
- Entry Conditions:
- <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>
- Outputs:
- <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>
- Artifacts Required (Deliverables):
- <e.g., Code Diff, Unit Tests, Migration Script, API Docs>
- Acceptance Evidence:
- <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>
- Success Criteria:
- <e.g., p95 < 300ms, coverage ≥ 80%>
Skill Composition
- Depends on: None
- Compatible with: None
- Conflicts with: None
- Related Skills: None
Quick Start
Assumptions
- Project uses Vite or compatible build tool
- TypeScript is configured
- Testing libraries are installed
Compatibility
- Node.js: 16+
- Vite: 4+
- TypeScript: 4.5+
- React: 16.8+
Test Scenario Matrix (QA Strategy)
| Type |
Focus Area |
Required Scenarios / Mocks |
| Unit |
Core Logic |
Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |
| Integration |
DB / API |
All external API calls or database connections must be mocked during unit tests |
| E2E |
User Journey |
Critical user flows to test |
| Performance |
Latency / Load |
Benchmark requirements |
| Security |
Vuln / Auth |
SAST/DAST or dependency audit |
| Frontend |
UX / A11y |
Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |
Technical Guardrails & Security Threat Model
1. Security & Privacy (Threat Model)
- Top Threats: Injection attacks, authentication bypass, data exposure
2. Performance & Resources
3. Architecture & Scalability
4. Observability & Reliability
Agent Directives
- Always clean up mocks
- Use vi.clearAllMocks() between tests
- Test one thing per test
- Keep tests independent
- Use descriptive test names
- Review snapshots before committing
Definition of Done (DoD) Checklist
Anti-patterns
Not Cleaning Up Mocks
// Bad: No cleanup
describe('Test', () => {
it('test', () => {
const mock = vi.fn();
// ...
});
});
// Good: Cleanup in afterEach
describe('Test', () => {
afterEach(() => {
vi.clearAllMocks();
});
it('test', () => {
const mock = vi.fn();
// ...
});
});
Testing Implementation Details
// Bad: Testing internals
it('should set internal state', () => {
expect(component._state).toBe('value');
});
// Good: Testing behavior
it('should display value', () => {
expect(screen.getByText('value')).toBeInTheDocument();
});
Reference Links & Examples
- Internal documentation and examples
- Official documentation and best practices
- Community resources and discussions
Versioning & Changelog
- Version: 1.0.0
- Changelog:
- 2026-02-22: Initial version with complete template structure
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: vitest-patterns3description: Vitest is a modern testing framework designed for the Vite ecosystem, Use when this capability is needed.4---56# Vitest Patterns78## Skill Profile9*(Select at least one profile to enable specific modules)*10- [ ] **DevOps**11- [x] **Backend**12- [ ] **Frontend**13- [ ] **AI-RAG**14- [ ] **Security Critical**1516## Overview17Vitest is a modern testing framework designed for the Vite ecosystem, but works with any project. It's 10-20x faster than Jest, with native TypeScript/ESM support and Jest-compatible API, making migration easy. This skill covers Vitest setup, basic testing, mocking, React component testing, async testing, snapshot testing, test utilities, and running tests.1819## Why This Matters20Vitest provides:21- **Speed**: 10-20x faster than Jest (Vite's transform pipeline)22- **Native ESM/TypeScript**: No transpilation config needed23- **Jest Compatible**: Same API, easy migration24- **Watch Mode**: Instant feedback with smart re-runs25- **UI Mode**: Visual test debugging interface2627## Core Concepts281. **Configuration**: Vite config integration292. **Test Environment**: jsdom, node, happy-dom303. **Globals**: describe, it, expect globally available314. **Mocking**: vi.fn(), vi.mock(), vi.spyOn()325. **Snapshots**: Snapshot testing for UI components336. **Coverage**: Built-in coverage with v8 or istanbul347. **Watch Mode**: Smart file watching and re-running3536## Inputs / Outputs / Contracts37* **Inputs**:38 - <e.g., env vars, request payload, file paths, schema>39* **Entry Conditions**:40 - <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>41* **Outputs**:42 - <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>43* **Artifacts Required (Deliverables)**:44 - <e.g., Code Diff, Unit Tests, Migration Script, API Docs>45* **Acceptance Evidence**:46 - <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>47* **Success Criteria**:48 - <e.g., p95 < 300ms, coverage ≥ 80%>4950## Skill Composition51* **Depends on**: None52* **Compatible with**: None53* **Conflicts with**: None54* **Related Skills**: None5556## Quick Start57#5859## Assumptions60- Project uses Vite or compatible build tool61- TypeScript is configured62- Testing libraries are installed6364## Compatibility65- **Node.js**: 16+66- **Vite**: 4+67- **TypeScript**: 4.5+68- **React**: 16.8+6970## Test Scenario Matrix (QA Strategy)7172| Type | Focus Area | Required Scenarios / Mocks |73| :--- | :--- | :--- |74| **Unit** | Core Logic | Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |75| **Integration** | DB / API | All external API calls or database connections must be mocked during unit tests |76| **E2E** | User Journey | Critical user flows to test |77| **Performance** | Latency / Load | Benchmark requirements |78| **Security** | Vuln / Auth | SAST/DAST or dependency audit |79| **Frontend** | UX / A11y | Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |808182## Technical Guardrails & Security Threat Model8384### 1. Security & Privacy (Threat Model)85* **Top Threats**: Injection attacks, authentication bypass, data exposure86- [ ] **Data Handling**: Sanitize all user inputs to prevent Injection attacks. Never log raw PII87- [ ] **Secrets Management**: No hardcoded API keys. Use Env Vars/Secrets Manager88- [ ] **Authorization**: Validate user permissions before state changes8990### 2. Performance & Resources91- [ ] **Execution Efficiency**: Consider time complexity for algorithms92- [ ] **Memory Management**: Use streams/pagination for large data93- [ ] **Resource Cleanup**: Close DB connections/file handlers in finally blocks9495### 3. Architecture & Scalability96- [ ] **Design Pattern**: Follow SOLID principles, use Dependency Injection97- [ ] **Modularity**: Decouple logic from UI/Frameworks9899### 4. Observability & Reliability100- [ ] **Logging Standards**: Structured JSON, include trace IDs `request_id`101- [ ] **Metrics**: Track `error_rate`, `latency`, `queue_depth`102- [ ] **Error Handling**: Standardized error codes, no bare except103- [ ] **Observability Artifacts**:104 - **Log Fields**: timestamp, level, message, request_id105 - **Metrics**: request_count, error_count, response_time106 - **Dashboards/Alerts**: High Error Rate > 5%107108109## Agent Directives1101. Always clean up mocks1112. Use vi.clearAllMocks() between tests1123. Test one thing per test1134. Keep tests independent1145. Use descriptive test names1156. Review snapshots before committing116117## Definition of Done (DoD) Checklist118119- [ ] Tests passed + coverage met120- [ ] Lint/Typecheck passed121- [ ] Logging/Metrics/Trace implemented122- [ ] Security checks passed123- [ ] Documentation/Changelog updated124- [ ] Accessibility/Performance requirements met (if frontend)125126127## Anti-patterns1281. **Not Cleaning Up Mocks**129 ```typescript130 // Bad: No cleanup131 describe('Test', () => {132 it('test', () => {133 const mock = vi.fn();134 // ...135 });136 });137138 // Good: Cleanup in afterEach139 describe('Test', () => {140 afterEach(() => {141 vi.clearAllMocks();142 });143144 it('test', () => {145 const mock = vi.fn();146 // ...147 });148 });149 ```1501512. **Testing Implementation Details**152 ```typescript153 // Bad: Testing internals154 it('should set internal state', () => {155 expect(component._state).toBe('value');156 });157158 // Good: Testing behavior159 it('should display value', () => {160 expect(screen.getByText('value')).toBeInTheDocument();161 });162 ```163164## Reference Links & Examples165166* Internal documentation and examples167* Official documentation and best practices168* Community resources and discussions169170171## Versioning & Changelog172173* **Version**: 1.0.0174* **Changelog**:175 - 2026-02-22: Initial version with complete template structure176177---178> Converted and distributed by [TomeVault](https://tomevault.io/claim/amnadtaowsoam) — claim your Tome and manage your conversions.179<!-- tomevault:4.0:skill_md:2026-04-13 -->