Angular Testing

Angular Testing

Writing automated tests is essential for building stable, enterprise-grade applications.

Tests ensure your code behaves exactly as expected and prevents future updates from breaking existing logic.

Angular provides a world-class testing environment right out of the box, powered by Jasmine and Karma (or Jest).


The TestBed Utility

Angular components rely heavily on Dependency Injection and HTML templates.

You cannot easily test them using standard vanilla JavaScript methods.

Angular provides the TestBed utility, which securely creates an isolated, simulated Angular environment specifically for your test!


Component Testing Example

Whenever you generate a component via the CLI, Angular automatically creates a .spec.ts testing file.

Inside this file, you use describe blocks to group tests, and it blocks for individual test cases.

Basic Component Test:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HeaderComponent } from './header.component';

describe('HeaderComponent', () => { let fixture: ComponentFixture<HeaderComponent>; let component: HeaderComponent;

beforeEach(() => { // Configures the simulated testing module TestBed.configureTestingModule({ declarations: [HeaderComponent] }); // Creates the component inside the test environment fixture = TestBed.createComponent(HeaderComponent); component = fixture.componentInstance; });

it('should create the component successfully', () => { // The assertion: checks if the component exists expect(component).toBeTruthy(); });

it('should have welcome text initialized', () => { // Validates the TypeScript logic expect(component.welcomeText).toEqual('Welcome!'); }); });


Testing the DOM

TestBed doesn't just test TypeScript variables; it tests the rendered HTML!

Using fixture.nativeElement, you can query the HTML DOM to guarantee that data bindings are working correctly.

If your component relies on inputs or outputs, you can manually trigger them and verify the DOM changes instantly using fixture.detectChanges().


Mocking Services

When testing a component, you should never make actual HTTP requests to a live database.

Instead, you should provide a "Mock" service to TestBed.

A Mock service intercepts the injection and returns fake data (like an array of fake users) purely for testing purposes.

This keeps your unit tests lightning fast and highly predictable.


Exercise 1 of 2

?

Which special Angular utility class is used to configure and initialize a simulated environment for unit testing?

Exercise 2 of 2

?

Why should you use a "Mock" service when testing a component?