Testing
Testing is crucial for maintaining code quality and preventing regressions. Vue provides excellent support for various testing strategies, from unit tests to end-to-end tests.Testing Strategy
A comprehensive testing strategy typically includes:- Unit Tests - Test individual components and functions in isolation
- Component Tests - Test components with their dependencies
- Integration Tests - Test how multiple components work together
- End-to-End Tests - Test complete user workflows in a real browser
Vitest - Fast Unit Testing
Vue core uses Vitest (version 4.0.18) as its test runner. Vitest is a blazing-fast unit test framework powered by Vite.Installation
Configuration
Vue core’svitest.config.ts configuration:
Test Projects
Vue core uses multiple test projects:Running Tests
Writing Unit Tests
Basic Test Structure
Custom Matchers
Vue core defines custom matchers inscripts/setup-vitest.ts:
Test Setup
ThebeforeEach and afterEach hooks manage test state:
Component Testing
Vue Test Utils
Vue’s official testing library:Mounting Components
Testing User Interactions
Testing Props
Testing Emitted Events
Testing Slots
Mocking Dependencies
Testing with Composition API
Testing with Plugins
Testing with Router
Testing with Pinia
Snapshot Testing
Coverage Reports
Generate coverage reports:End-to-End Testing
Playwright
For E2E testing, Playwright is recommended:Cypress
Alternatively, use Cypress:Best Practices
- Test behavior, not implementation - Focus on what users see and do
- Keep tests simple and focused - One assertion per test when possible
- Use meaningful test descriptions - Describe what the test verifies
- Mock external dependencies - Keep tests fast and isolated
- Test edge cases - Don’t just test the happy path
- Maintain test coverage - Aim for 80%+ coverage on critical paths
- Run tests in CI/CD - Catch regressions before they reach production
- Use TypeScript in tests - Leverage type safety