🅰️ Angular Intermediate

What is Angular testing with Jasmine and Karma?

Answer

Angular uses Jasmine (testing framework) + Karma (test runner) by default for unit testing. Component tests use TestBed to create a test Angular environment. Basic component test: describe("UserCardComponent", () => { let component: UserCardComponent; let fixture: ComponentFixture<UserCardComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [UserCardComponent] // standalone; or declarations for module-based }).compileComponents(); fixture = TestBed.createComponent(UserCardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it("should display username", () => { component.user = { name: "Alice" }; fixture.detectChanges(); const nameEl = fixture.debugElement.query(By.css(".name")); expect(nameEl.nativeElement.textContent).toContain("Alice"); }); });. Testing services: inject via TestBed: TestBed.inject(UserService). Mock dependencies: const mockHttp = jasmine.createSpyObj("HttpClient", ["get"]); mockHttp.get.and.returnValue(of([{ name: "Alice" }]));. Testing HTTP: use HttpClientTestingModule and HttpTestingController to mock HTTP requests. Testing Observables: use the async helper or fakeAsync + tick(). spyOn: spyOn(service, "getUsers").and.returnValue(of([]));. Angular 16+ testing with Jest: ng add @angular-builders/jest — replace Karma with Jest for faster test execution, better DX, snapshot testing. Running tests: ng test — watch mode; ng test --code-coverage — generate coverage report.