Testing Basics
Imagine building a bridge. Would you let people cross it without testing it first? Of course not! Same with your Angular application – testing ensures your code works correctly and continues to work as you make changes.
Angular is designed with testing in mind. It provides tools like TestBed, ComponentFixture, and integration with Jasmine and Karma.
Types of Tests
- Unit Tests – Test individual components, services, pipes in isolation.
- Integration Tests – Test how multiple pieces work together.
- End-to-End (E2E) Tests – Test the entire application from user perspective.
Setting Up Testing
When you create an Angular project with CLI, testing is already configured with Jasmine and Karma. Test files end with
.spec.ts.Testing a Component
Here's a simple component:
@Component({
selector: 'app-greeting',
template: '<h1>Hello {{name}}!</h1>'
})
export class GreetingComponent {
@Input() name: string;
}
Now test it (
greeting.component.spec.ts):describe('GreetingComponent', () => {
let component: GreetingComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [GreetingComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(GreetingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should display the name', () => {
component.name = 'Angular';
fixture.detectChanges();
const h1 = fixture.nativeElement.querySelector('h1');
expect(h1.textContent).toContain('Hello Angular!');
});
});
Testing a Service
Services are often easier to test because they're plain TypeScript classes.
describe('DataService', () => {
let service: DataService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(DataService);
});
it('should add an item', () => {
service.addItem('test');
expect(service.getItems()).toContain('test');
});
});
Testing with HTTP
Use
HttpClientTestingController to mock HTTP requests.let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [DataService]
});
service = TestBed.inject(DataService);
httpMock = TestBed.inject(HttpTestingController);
});
it('should fetch posts', () => {
const mockPosts = [{ id: 1, title: 'Test' }];
service.getPosts().subscribe(posts => {
expect(posts).toEqual(mockPosts);
});
const req = httpMock.expectOne('/api/posts');
expect(req.request.method).toBe('GET');
req.flush(mockPosts);
});
Two Minute Drill
- Angular uses Jasmine (testing framework) and Karma (test runner).
- Test files end with .spec.ts.
- TestBed configures testing modules.
- ComponentFixture gives access to component and its template.
- HttpClientTestingModule mocks HTTP requests.
- Run tests with `ng test`.
Need more clarification?
Drop us an email at career@quipoinfotech.com
