Overview
Count App uses Vitest as its testing framework, configured through Angular’s built-in test builder. Vitest provides a fast, modern testing experience with features like:- Fast execution with smart watch mode
- ESM-first design
- Compatible with Jest’s API
- Built-in TypeScript support
Running Tests
Run all tests using the npm test script:The test command uses the
@angular/build:unit-test builder configured in angular.json.Test Configuration
TypeScript Configuration
The test setup is configured in tsconfig.spec.json:tsconfig.spec.json
- Extends the base TypeScript configuration
- Includes Vitest global types (describe, it, expect, etc.)
- Only includes
.spec.tsand.d.tsfiles from the src directory
Angular Test Builder
The test builder is configured in angular.json:angular.json
Writing Tests
Basic Component Test
Here’s the example test from src/app/app.spec.ts:src/app/app.spec.ts
Test Structure
Set up TestBed
Use
TestBed.configureTestingModule() to configure the testing module with the component and its dependencies:Test Patterns
Testing Component Creation
Testing Template Rendering
Always call
await fixture.whenStable() when testing asynchronous operations or template bindings to ensure all changes are applied.Testing User Interactions
For testing button clicks and counter updates:Best Practices
Use describe blocks for organization
Use describe blocks for organization
Group related tests together:
Clean up after each test
Clean up after each test
Use
beforeEach and afterEach for setup and cleanup:Test behavior, not implementation
Test behavior, not implementation
Focus on testing what the component does, not how it does it:
VSCode Integration
The project includes a VSCode launch configuration for running tests (see .vscode/launch.json):- Open the Run and Debug panel (Ctrl+Shift+D)
- Select “ng test” from the dropdown
- Press F5 or click the play button
Troubleshooting
Tests fail with 'Cannot find module'
Tests fail with 'Cannot find module'
Ensure your tsconfig.spec.json includes the correct files:
Vitest globals not recognized
Vitest globals not recognized
Make sure
vitest/globals is in your types array in tsconfig.spec.json:Template changes not reflected in tests
Template changes not reflected in tests
Call
fixture.detectChanges() to trigger change detection:Next Steps
Building for Production
Learn how to build and deploy your application