Angular Tutorial
Unit Testing Basics (Jasmine & Karma)
Unlike many Javascript libraries where testing is an afterthought, Angular ships with a complete Unit Testing framework configured from day one! Every time you run ng generate component user, Angular automatically creates a user.component.spec.ts test file alongside it.
The Stack: Jasmine and Karma
Historically, Angular uses Jasmine as the behavior-driven testing syntax (the code you write) and Karma as the test runner (the program that opens a browser and executes the Jasmine code).Note: Modern teams often swap this for Jest, but the syntax is nearly identical.
Running Tests
To execute the entire test suite of your application, use the CLI:
ng testThis compiles your app, opens Chrome, runs all `.spec.ts` files, and prints a success report to the terminal.
The TestBed
Because Angular Components rely heavily on Dependency Injection, you cannot simply instantiate a class (e.g. new DashboardComponent()) because it would fail without its injected Services! Angular uses TestBed to securely construct an isolated environment to test the component in.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ButtonComponent } from './button.component';
describe('ButtonComponent', () => {
let component: ButtonComponent;
let fixture: ComponentFixture<ButtonComponent>;
beforeEach(() => {
// 1. Configure the isolated testing module
TestBed.configureTestingModule({
imports: [ButtonComponent]
});
// 2. Create the component physically
fixture = TestBed.createComponent(ButtonComponent);
component = fixture.componentInstance;
// 3. Trigger Angular's data-binding detection
fixture.detectChanges();
});
// 4. The actual test
it('should create the component', () => {
expect(component).toBeTruthy();
});
it('should display the correct label', () => {
component.label = "Submit";
fixture.detectChanges(); // Re-render HTML!
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('button')?.textContent).toContain('Submit');
});
});Mocking Services
A core rule of Unit Testing: You must test the Component in isolation. If your Component hits a Database API, you must NOT hit the real Database during tests! You use Mocks (or jasmine spies) to fake the Service response natively using Angular's Dependency Injection system.
Conclusion
Once your application's logic is fully tested and verified, you are ready to ship it to production! Let's explore how to securely optimize and launch an Angular application in our final chapter: Deployment.