TExcelTAD
Home › Angular › Testing Angular Apps

Testing Angular Apps

Every ng generate command creates a .spec.ts file next to the new code. Those are unit tests: small, fast checks that a pipe formats correctly, a service computes the right total, or a component renders the expected text. Running them on every change gives you the confidence to refactor.

Running the tests

bash · try it yourself
ng test --watch=false
Chrome Headless 131.0.0.0 (Linux x86_64): Executed 0 of 9 SUCCESS (0 secs / 0 secs)
Chrome Headless 131.0.0.0 (Linux x86_64): Executed 9 of 9 SUCCESS (0.187 secs / 0.142 secs)
TOTAL: 9 SUCCESS

ng test builds the specs and runs them in a browser. Without --watch=false it stays open and re-runs on every save.

Note: Projects generated with Angular 20 and earlier use Jasmine + Karma by default. Newer CLI versions default to Vitest. The test code — describe, it, expect, TestBed — looks almost the same in both; mainly the spy API differs (jasmine.createSpy vs vi.fn).

Anatomy of a spec

ts
describe('TruncatePipe', () => {          // a suite
  const pipe = new TruncatePipe();

  it('keeps short text unchanged', () => { // a test
    expect(pipe.transform('Hi', 10)).toBe('Hi');
  });

  it('cuts long text and adds an ellipsis', () => {
    expect(pipe.transform('Hello Angular world', 5)).toBe('Hello…');
  });
});
Function Purpose
describe(name, fn) Group related tests
it(name, fn) One test case
beforeEach(fn) Setup that runs before every test in the group
expect(x).toBe(y) Strict equality (===)
expect(x).toEqual(y) Deep equality for objects/arrays
expect(x).toContain(y) Array item or substring
expect(fn).toThrow() The function throws

Testing plain logic

Pipes, services and validators are classes and functions, so you test them without any Angular machinery. To show what a test runner does, here's a tiny one in plain TypeScript running real tests against a cart service:

ts · try it yourself
const results: string[] = [];
let prefix = '';

function describe(name: string, fn: () => void) { prefix = name; fn(); prefix = ''; }
function it(name: string, fn: () => void) {
  try { fn(); results.push(`✔ ${prefix} ${name}`); }
  catch (e) { results.push(`✘ ${prefix} ${name} — ${(e as Error).message}`); }
}
function expect<T>(actual: T) {
  return {
    toBe(expected: T) {
      if (actual !== expected) throw new Error(`expected ${String(expected)} but got ${String(actual)}`);
    },
  };
}

class CartService {
  private items: { name: string; price: number; qty: number }[] = [];
  add(name: string, price: number, qty = 1) { this.items.push({ name, price, qty }); }
  total() { return this.items.reduce((s, i) => s + i.price * i.qty, 0); }
  count() { return this.items.length; }
}

describe('CartService', () => {
  it('starts empty', () => expect(new CartService().total()).toBe(0));
  it('sums price × quantity', () => {
    const cart = new CartService();
    cart.add('Pen', 2, 3);
    cart.add('Book', 15);
    expect(cart.total()).toBe(21);
  });
  it('counts lines, not units', () => {
    const cart = new CartService();
    cart.add('Pen', 2, 3);
    expect(cart.count()).toBe(3); // deliberately wrong expectation
  });
});

results.forEach((r) => console.log(r));
✔ CartService starts empty
✔ CartService sums price × quantity
✘ CartService counts lines, not units — expected 3 but got 1

A failing test points straight at the wrong assumption. (Here the test was wrong — count() returns lines, so the expectation should be 1.)

Testing a component with TestBed

TestBed creates a component inside a small test environment so you can inspect its rendered DOM. Here is the component under test:

ts
// greeting.ts
@Component({
  selector: 'app-greeting',
  template: `
    <h2>Hello, {{ name() }}!</h2>
    <button (click)="waves.update((n) => n + 1)">👋</button>
    <p>Waves: {{ waves() }}</p>
  `,
})
export class Greeting {
  name = input.required<string>();
  waves = signal(0);
}

And its spec:

angular · try it yourself
// greeting.spec.ts
import { TestBed } from '@angular/core/testing';
import { Greeting } from './greeting';

describe('Greeting', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({ imports: [Greeting] }).compileComponents();
  });

  it('renders the name input', async () => {
    const fixture = TestBed.createComponent(Greeting);
    fixture.componentRef.setInput('name', 'Hoa');
    await fixture.whenStable();

    const el: HTMLElement = fixture.nativeElement;
    expect(el.querySelector('h2')?.textContent).toContain('Hello, Hoa');
  });

  it('increments the wave counter on click', async () => {
    const fixture = TestBed.createComponent(Greeting);
    fixture.componentRef.setInput('name', 'Hoa');
    fixture.nativeElement.querySelector('button').click();
    await fixture.whenStable();
    expect(fixture.nativeElement.textContent).toContain('Waves: 1');
  });
});
Greeting
  ✔ renders the name input
  ✔ increments the wave counter on click

Executed 2 of 2 SUCCESS

Key APIs:

API Purpose
TestBed.configureTestingModule({ imports, providers }) Set up what the component needs
TestBed.createComponent(C) Create a ComponentFixture
fixture.componentRef.setInput(name, value) Set an input (works with signal inputs)
await fixture.whenStable() Wait for change detection and pending work
fixture.nativeElement The rendered DOM element
TestBed.inject(Service) Get a service instance in the test

Replacing dependencies

Pass fakes through providers so a component test doesn't hit the network:

ts
const fakeApi = { list: () => of([{ id: 1, title: 'Test todo', completed: false }]) };

TestBed.configureTestingModule({
  imports: [TodoList],
  providers: [{ provide: TodoApi, useValue: fakeApi }],
});

For services that use HttpClient, Angular provides provideHttpClientTesting() and HttpTestingController to assert which requests were made and to flush fake responses.

Tip: Test behaviour, not implementation. Check what the user would see ("the list shows 3 items") rather than private fields — tests then survive refactoring.

Test yourself

Which matcher compares two arrays by their contents?

  1. toBe
  2. toEqual
  3. toBeTruthy
  4. toThrow

How do you set a signal input on a component created with TestBed?

  1. fixture.componentInstance.name = 'x'
  2. fixture.componentRef.setInput('name', 'x')
  3. TestBed.setInput('x')
  4. Inputs cannot be set in tests

How do you stop a component test from calling the real API service?

  1. Delete the service
  2. Provide a fake with { provide: TodoApi, useValue: fakeApi }
  3. Run tests offline
  4. Use ViewEncapsulation.None