Unit tests help you verify that your Angular components, services, and pipes work as expected. Angular includes testing tools like Jasmine, Karma, and TestBed. You use these tools to run isolated tests that validate logic, events, and template behavior.
This tutorial shows how to:
- Set up testing environment
- Write component tests
- Test services
- Test form validation
- Run tests efficiently
Why Unit Testing Matters
Unit tests catch problems early. They help you prevent regressions. They make refactoring safe. They improve code quality. Angular’s CLI creates a testing environment by default, so you can start testing immediately.
Step 1: Understand Angular Test Structure
Angular uses:
- Jasmine for test syntax
- Karma as the test runner
- TestBed to create Angular testing modules
A basic test file looks like this:
describe('MyComponent', () => {
it('should create component', () => {
expect(true).toBeTrue();
});
});
Your Angular CLI automatically generates test files with this format.
Step 2: Write a Unit Test for a Component
Example component:
@Component({ selector: 'app-counter', template: `<button (click)="inc()">+</button>{{count}}` })
export class CounterComponent {
count = 0;
inc() { this.count++; }
}
Test file:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CounterComponent } from './counter.component';
describe('CounterComponent', () => {
let component: CounterComponent;
let fixture: ComponentFixture<CounterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [CounterComponent]
}).compileComponents();
fixture = TestBed.createComponent(CounterComponent);
component = fixture.componentInstance;
});
it('should create component', () => {
expect(component).toBeTruthy();
});
it('should increase count', () => {
component.inc();
expect(component.count).toBe(1);
});
});
This test validates component creation and method logic.
Step 3: Test a Service
Service example:
@Injectable({ providedIn: 'root' })
export class MathService {
add(a: number, b: number) { return a + b; }
}
Service test:
import { TestBed } from '@angular/core/testing';
import { MathService } from './math.service';
describe('MathService', () => {
let service: MathService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MathService);
});
it('should add numbers', () => {
expect(service.add(2, 3)).toBe(5);
});
});
This verifies service logic without a component.
Step 4: Test Reactive Forms
Component example:
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email])
});
Test example:
it('should mark email invalid if empty', () => {
component.form.controls['email'].setValue('');
expect(component.form.controls['email'].valid).toBeFalse();
});
it('should mark email valid when correct', () => {
component.form.controls['email'].setValue('test@test.com');
expect(component.form.controls['email'].valid).toBeTrue();
});
Step 5: Test DOM Interaction
it('should increment count when button clicked', () => {
const button = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges();
expect(component.count).toBe(1);
});
This test validates UI interaction.
Step 6: Run All Tests
Use Angular CLI to execute tests.
ng test
Karma opens a browser window and shows test results in real time.
Summary
You learned how to add unit tests in Angular. You wrote:
- Component tests
- Service tests
- Reactive form tests
- DOM interaction tests
These patterns help you build reliable Angular applications. They protect your codebase as it grows.
I hope you like this article...
Happy coding! 🚀
0 Comments