Learn Angular · 13/14

Testing Angular Applications

8 min read

Welcome back. Today we enter a domain that separates the hobbyist from the professional engineer: Testing.

In the software industry, writing code is often the easy part. Ensuring that code behaves correctly under various conditions, and continues to behave correctly as the application grows, is the true challenge. Without tests, every new feature carries the risk of breaking an existing one—a phenomenon known as regression.

We will approach this strictly and methodically, building from the smallest unit of logic up to full user simulation.


1. Unit Testing Fundamentals: Jasmine and Karma 🧪

The Problem

Imagine you write a function that calculates the total price of items in a shopping cart. You verify it works by running the app, clicking buttons, and looking at the screen. This is manual testing. It is slow, prone to human error, and unrepeatable. If you change the logic six months later, you might forget to check a specific edge case (e.g., negative quantities).

The Solution

Unit Testing involves writing code that verifies other code. We isolate a small "unit" (a function or a class) and assert that for a given input, it produces a specific output. This process is automated and instantaneous.

The Ecosystem

Angular comes pre-configured with two tools:

  1. Jasmine: The testing framework. It provides the syntax for writing tests (describe, it, expect).
  2. Karma: The test runner. It spawns a browser, executes the tests, and reports the results to your terminal.

Note: While Jest is a popular modern alternative that runs faster (by simulating the DOM instead of using a real browser), we will focus on the default Angular setup to ensure stability.

Anatomy of a Test

Jasmine tests reside in .spec.ts files. Let us examine the syntax:

  1. describe(): Defines a suite (a group of related tests).
  2. it(): Defines a spec (a specific test case).
  3. expect(): Defines an expectation (the assertion).

Example: Testing a Simple Class

Suppose we have a plain TypeScript class:

typescript
// calculator.ts
export class Calculator {
  add(a: number, b: number): number {
    return a + b;
  }
}

Here is how we test it:

typescript
// calculator.spec.ts
import { Calculator } from './calculator';

describe('Calculator', () => {
  let calc: Calculator;

  // Setup: Runs before every 'it' block
  beforeEach(() => {
    calc = new Calculator();
  });

  it('should return 4 when adding 2 and 2', () => {
    const result = calc.add(2, 2);
    expect(result).toBe(4); // The Assertion
  });

  it('should handle negative numbers', () => {
    const result = calc.add(-1, 5);
    expect(result).toBe(4);
  });
});

To run these tests in a standard Angular CLI project, execute:

bash
ng test

Historical Fact: The first recorded software "bug" was a literal moth found trapped in a relay of the Harvard Mark II computer in 1947. While Grace Hopper popularized the term, engineers had been using the word "bug" to describe glitches since the days of Thomas Edison.


2. Testing Components and the TestBed ⚙️

The Problem

Testing a plain class is straightforward. However, an Angular Component is not just a class. It interacts with the DOM (HTML templates) and relies on Dependency Injection (DI). If you simply utilize new Component(), you miss the HTML rendering and the lifecycle hooks (ngOnInit, etc.).

The Solution

Angular provides the TestBed. The TestBed is the most important concept in Angular testing. It creates a dynamic, scoped Angular module specifically for the test suite. It allows you to configure the dependency injection system and compile the component's HTML.

Step-by-Step Component Test

Let us assume we have a BannerComponent that displays a title.

typescript
// banner.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-banner',
  template: '<h1>{{ title }}</h1>'
})
export class BannerComponent {
  title = 'Test Tour';
}

We must configure the testing module to simulate the Angular runtime environment.

typescript
// banner.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BannerComponent } from './banner.component';

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

  beforeEach(async () => {
    // 1. Configure the Testing Module
    await TestBed.configureTestingModule({
      declarations: [ BannerComponent ] // Declare the component to be tested
    })
    .compileComponents(); // Compile template and css
  });

  beforeEach(() => {
    // 2. Create the component fixture
    fixture = TestBed.createComponent(BannerComponent);
    
    // 3. Access the component instance
    component = fixture.componentInstance; 
    
    // 4. Trigger initial data binding (ngOnInit)
    fixture.detectChanges(); 
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should render title', () => {
    // Access the Native Element (The DOM)
    const compiled = fixture.nativeElement as HTMLElement;
    
    // querySelector checks the actual rendered HTML
    expect(compiled.querySelector('h1')?.textContent).toContain('Test Tour');
  });
});

Key Utilities

  • ComponentFixture: A test harness for interacting with the created component and its surrounding environment.
  • fixture.detectChanges(): In production, Angular detects changes automatically. In tests, you must manually tell Angular when to run change detection. This gives you fine-grained control over the component lifecycle.
  • fixture.nativeElement: Gives access to the underlying DOM element directly.

3. Testing Services and Mocking Dependencies 📡

The Problem

Services often depend on external resources, such as HTTP calls to a backend API. If you test a service by allowing it to make real network requests:

  1. Tests will be slow.
  2. Tests will fail if the server is down (flakiness).
  3. You might accidentally modify production data.

The Solution

Mocking. We replace the real dependencies with simulated ones. We spy on the methods to ensure they are called correctly, and we force them to return specific values to test how our service handles data or errors.

Implementation: SpyObj

Suppose we have a UserService that depends on HttpClient to fetch data. We want to test UserService, but we do not want to use the real HttpClient.

typescript
// user.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private http: HttpClient) {}

  getUsers() {
    return this.http.get<any[]>('/api/users');
  }
}

In our test, we create a "Spy Object" for the HttpClient.

typescript
// user.service.spec.ts
import { TestBed } from '@angular/core/testing';
import { UserService } from './user.service';
import { HttpClient } from '@angular/common/http';
import { of } from 'rxjs'; // 'of' creates an observable from data

describe('UserService', () => {
  let service: UserService;
  let httpClientSpy: jasmine.SpyObj<HttpClient>;

  beforeEach(() => {
    // Create a fake HttpClient with a 'get' method
    const spy = jasmine.createSpyObj('HttpClient', ['get']);

    TestBed.configureTestingModule({
      providers: [
        UserService,
        // When the app asks for HttpClient, give it the spy instead
        { provide: HttpClient, useValue: spy } 
      ]
    });

    service = TestBed.inject(UserService);
    httpClientSpy = TestBed.inject(HttpClient) as jasmine.SpyObj<HttpClient>;
  });

  it('should return expected users (HttpClient called once)', (done: DoneFn) => {
    const expectedUsers = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
  
    // Tell the spy: When .get() is called, return this Observable immediately
    httpClientSpy.get.and.returnValue(of(expectedUsers));

    service.getUsers().subscribe({
      next: users => {
        expect(users).toEqual(expectedUsers);
        done();
      },
      error: done.fail
    });

    // Verify the method was actually called
    expect(httpClientSpy.get.calls.count()).toBe(1);
  });
});

Industry Standard: Never perform actual HTTP requests in Unit Tests. Always mock the communication layer.


4. End-to-End (E2E) Testing Overview 🤖

The Problem

Unit tests verify that small parts work in isolation. However, a car engine might work perfectly on a stand, but fail to turn the wheels when installed in the chassis. Similarly, your component might pass unit tests, but fail when integrated with the routing system, authentication guards, and the real database.

The Solution

End-to-End (E2E) Testing. This simulates a real user interacting with your application in a real browser. It visits URLs, clicks elements, types in forms, and validates the visual outcome.

Tools: Cypress or Playwright

Historically, Angular used Protractor. Protractor is now deprecated. The industry standard has shifted to Cypress and Playwright.

  • Cypress: runs inside the browser with your application. It is known for its excellent developer experience and ease of debugging.
  • Playwright: runs outside the browser and controls it via protocols. It is faster and supports multi-tab/multi-browser testing better.

Example: Cypress Syntax

Cypress tests read almost like English sentences.

  1. Visit the page.
  2. Get an element.
  3. Interact (click/type).
  4. Assert the state.
javascript
// e2e/login.cy.ts

describe('Login Flow', () => {
  it('should log in successfully', () => {
    // 1. Visit the page
    cy.visit('/login');

    // 2. Type into inputs
    cy.get('input[name="username"]').type('testuser');
    cy.get('input[name="password"]').type('password123');

    // 3. Click the button
    cy.get('button[type="submit"]').click();

    // 4. Assert redirection or UI change
    cy.url().should('include', '/dashboard');
    cy.get('h1').should('contain', 'Welcome, testuser');
  });
});

To run E2E tests (assuming Cypress is configured):

bash
ng e2e
# or
npx cypress open

Interesting Fact

Did you know that "It works on my machine" is such a prevalent problem that it effectively gave birth to the technology of Docker containers? Testing attempts to solve the logic errors; Containers attempt to solve the environment errors. Using both makes you an invincible engineer.

Summary

  1. Unit Tests (Jasmine/Karma): Test functions and classes in isolation. Fast and precise.
  2. TestBed: The bridge between your test code and the Angular framework features (DOM/DI).
  3. Mocking: Faking external dependencies (API calls) to keep tests pure and fast.
  4. E2E (Cypress): Simulating real user flows to catch integration issues.

References & Further Reading

Proceed to the challenge. Ensure your code is robust. Happy testing. 🍵

Challenge

Challenge: Test an Angular Component with a Mocked Service

You are tasked with writing a unit test for an Angular component, UserProfileComponent. This component fetches user data from a UserService on initialization and displays it in its template.

Your goal is to test the component's rendering logic without making an actual HTTP call. To achieve this, you must mock the UserService.

Requirements:

  1. Configure the Test Environment: Use TestBed to set up a testing module for the UserProfileComponent.
  2. Mock the Dependency: Create a mock for the UserService using jasmine.createSpyObj. The mock must have a getUser method.
  3. Provide the Mock: In your TestBed configuration, instruct Angular's dependency injector to use your mock service instead of the real UserService.
  4. Simulate Data: Configure the mocked getUser method to return an Observable that immediately emits a predefined user object: { name: 'John Smith', email: '[email protected]' }.
  5. Write the Assertion: In the test case (it block), perform the following steps:
    • Trigger Angular's change detection cycle.
    • Query the component's rendered DOM to find the elements displaying the user's name and email.
    • Assert that the content of these elements correctly matches the data from your mock user object.

Expected result

Your code should correctly implement the Jasmine test suite for the UserProfileComponent.

A correct solution will contain the following elements:

  1. beforeEach Configuration:

    • A jasmine.createSpyObj call to create mockUserService with a ['getUser'] method.
    • The TestBed.configureTestingModule method is called with an object containing:
      • declarations: [UserProfileComponent] to include the component in the test module.
      • providers: [{ provide: UserService, useValue: mockUserService }] to replace the real UserService with the mock.
    • The mock's getUser method is configured to return the test data: mockUserService.getUser.and.returnValue(of(mockUser));.
  2. it Block Implementation:

    • A call to fixture.detectChanges() to trigger the ngOnInit lifecycle hook and render the component's template.
    • The use of fixture.nativeElement to access the rendered DOM.
    • querySelector is used to find the h1 and p elements by their IDs (#userName and #userEmail).
    • expect() assertions are used to verify that the textContent of the selected elements matches the name and email properties of the mockUser object.
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.