73. Testing Fundamentals: Setup and TestBed
Testing is vital for ensuring application quality and maintainability. Angular uses Jasmine (for the testing framework) and Karma (for the test runner).
Types of Tests
- Unit Tests: Focus on single, isolated units of code (components, services, pipes, etc.).
- Integration Tests: Check how units interact (e.g., a component using a service).
- End-to-End (E2E) Tests: Simulate real user workflow in a browser.
The Angular TestBed
TestBed is the most important utility for unit testing Angular components and services. It creates a testing module environment mirroring an NgModule.
typescript import { TestBed } from '@angular/core/testing'; import { ComponentFixture } from '@angular/core/testing';
// We are testing AppComponent import { AppComponent } from './app.component';
describe('AppComponent', () => {
let fixture: ComponentFixture
beforeEach(async () => { // Configure the testing module environment await TestBed.configureTestingModule({ // Declare components, directives, and pipes needed for testing declarations: [AppComponent], // Provide services needed (often mocked) providers: [], // Import modules needed (e.g., RouterTestingModule) imports: [] }).compileComponents(); // Compile component templates (necessary for templateUrl)
// Create the component instance and its host fixture
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
});
it('should create the app', () => { expect(component).toBeTruthy(); });
it(should have the title 'my-app', () => {
expect(component.title).toEqual('my-app');
});
});
beforeEach runs before every test (it), ensuring a clean state for each test case.