Testing Angular

ng test runs every *.spec.ts file; since Angular 21 ng new uses Vitest, and older projects (v20 and earlier) use Jasmine (describe, it, expect) with the Karma…

Every time you change a line in the cart, you're tempted to click every button again: Order, Remove, Send. Five changes later you start skipping a click or two, and the bug slips through.

An automated test does those clicks for you. It's code that uses your component or service the way a buyer would, then checks the result. Picture Jali's checklist before the stall opens: light the stove, the empty scale must read 0, the bell must ring. Same order every day, and if one fails, he knows before buyers arrive. ng test runs all those checklists in seconds.

ng test and .spec.ts files

Every *.spec.ts file holds tests. ng test finds them all, builds them, then runs them. Since Angular 21, ng new uses Vitest, which runs the tests in Node.js with jsdom (a simulated DOM), without a browser. In older projects (v20 and earlier), the test framework is Jasmine and the runner is Karma, which opens Chrome. Vitest and Jasmine both give you describe, it and expect, and TestBed is the same.

describe('CartStore', () => {           // a group of tests
  it('works out the count and total from the items', () => {   // one test
    expect(store.count()).toBe(1)           // one check
  })
})

Here's how ng test --watch=false (one run) ends for the Jali project with four spec files (5 tests):

 Test Files  4 passed (4)
      Tests  5 passed (5)

Without --watch=false, ng test in a terminal keeps waiting, then reruns the tests every time you save a file. In older projects, ng test --watch=false --browsers=ChromeHeadless runs Karma in Chrome without a window and writes Executed 5 of 5 SUCCESS, then TOTAL: 5 SUCCESS.

Testing a component: TestBed and detectChanges

// src/app/counter.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { CounterComponent } from './counter'

describe('CounterComponent', () => {
  let fixture: ComponentFixture<CounterComponent>
  let el: HTMLElement

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [CounterComponent],
    }).compileComponents()

    fixture = TestBed.createComponent(CounterComponent)
    el = fixture.nativeElement
    fixture.detectChanges()
  })

  it('shows Count: 0 at the start', () => {
    expect(el.querySelector('p')?.textContent).toBe('Count: 0')
  })

  it('goes up to Count: 1 after +1 is clicked', () => {
    el.querySelector('button')!.click()
    fixture.detectChanges()
    expect(el.querySelector('p')?.textContent).toBe('Count: 1')
  })
})
What's forgotten Vitest's message
the first detectChanges() expected '' to be 'Count: 0' // Object.is equality
detectChanges() after the click expected 'Count: 0' to be 'Count: 1' // Object.is equality

The second row is the one you'll hit most. The click does raise count, but the DOM only changes when detectChanges() is called (or after await fixture.whenStable()), so the <p> still says Count: 0. Vitest writes FAIL with the test's name, then AssertionError: and the message in the table, and at the end Tests 1 failed | 4 passed (5). In older projects, Jasmine writes Expected 'Count: 0' to be 'Count: 1'. and Karma ends with TOTAL: 1 FAILED, 4 SUCCESS.

One click isn't enough to prove "add one", either. If increment() is miswritten as this.count.set(1), the test above stays green; only a test that clicks twice fails, with expected 'Count: 1' to be 'Count: 2' // Object.is equality.

Testing a service: TestBed.inject

describe('CartStore', () => {
  let store: CartStore

  beforeEach(() => {
    store = TestBed.inject(CartStore)
  })

  it('works out the count and total from the items', () => {
    store.add({ name: 'Chocolate Cheese Pancake', price: 8 })
    store.add({ name: 'Special Egg Pancake', price: 10 })
    store.remove(0)
    expect(store.count()).toBe(1)
    expect(store.total()).toBe(10)
  })
})

A service has no template, so there's no detectChanges. TestBed.inject hands you its instance, like inject() in the app.

Testing HTTP: HttpTestingController

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [provideHttpClient(), provideHttpClientTesting()],
  })
  api = TestBed.inject(MenuApi)
  httpMock = TestBed.inject(HttpTestingController)
})

afterEach(() => {
  httpMock.verify()
})

it('fetches the menu with GET /api/menu', () => {
  let result: Menu[] = []
  api.getMenu().subscribe((menu) => (result = menu))

  const req = httpMock.expectOne('/api/menu')
  expect(req.request.method).toBe('GET')
  req.flush([{ id: 2, name: 'Special Egg Pancake', price: 10, stock: 6 }])

  expect(result.length).toBe(1)
  expect(result[0].name).toBe('Special Egg Pancake')
})

A wrong URL (/api/menus) fails with Error: Expected one matching request for criteria "Match URL: /api/menus", found none. Requests received are: GET /api/menu. A forgotten flush fails with expected +0 to be 1 // Object.is equality, because result is never filled. Watch out when the expect sits inside subscribe: without flush, that expect never runs, and the test passes with no warning at all from Vitest. In older projects, Karma only writes WARN: 'Spec '...' has no expectations.'

Time: vi.useFakeTimers and fakeAsync

The "Added to cart" notice disappears by itself through setTimeout(..., 2000). The test doesn't need to wait two seconds:

it('disappears by itself after 2 seconds', () => {
  vi.useFakeTimers()
  const fixture = TestBed.createComponent(Notice)
  const el: HTMLElement = fixture.nativeElement
  fixture.detectChanges()

  el.querySelector('button')!.click()
  fixture.detectChanges()
  expect(el.querySelector('.notice')).not.toBeNull()

  vi.advanceTimersByTime(2000)
  fixture.detectChanges()
  expect(el.querySelector('.notice')).toBeNull()
  vi.useRealTimers()
})

vi.useFakeTimers() installs a fake clock, vi.advanceTimersByTime(2000) moves it 2,000 ms forward at once, and vi.useRealTimers() puts the real clock back. vi.advanceTimersByTime(1999) fails with expected <p class="notice"></p> to be null: the timer isn't due yet. Use detectChanges() here: with a fake clock, await fixture.whenStable() keeps waiting until a timeout, because Angular also schedules the update with a timer. Older projects (v20 and earlier) use fakeAsync(() => { ... }) and tick(2000). In a new ng new project, fakeAsync fails with Error: zone-testing.js is needed for the fakeAsync() test helper but could not be found., because it needs zone.js.

⚠️ Why the test is red, or green when the code is wrong

TL;DR: ng test runs every *.spec.ts file; since Angular 21 ng new uses Vitest, and older projects (v20 and earlier) use Jasmine (describe, it, expect) with the Karma runner. TestBed.configureTestingModule({ imports: [Component] }) sets up the test, TestBed.createComponent builds the component, and fixture.detectChanges() updates the template after every action (or await fixture.whenStable() since Angular 21). Services come from TestBed.inject. HTTP is tested without a server through provideHttpClientTesting() and HttpTestingController (expectOne, flush, verify). Time moves forward with vi.useFakeTimers() and vi.advanceTimersByTime(2000), or with fakeAsync and tick(2000) in older projects. Test with more than one action so bugs like set(1) show up.

⚡ TestBed and detectChanges

Write:

fixture = TestBed.createComponent(CounterComponent)
el = fixture.nativeElement
fixture.detectChanges()
Guess first: the +1 button is clicked, but there's no fixture.detectChanges() after it. What does the <p> say?

Still Count: 0. The click does raise count, but the DOM only changes when detectChanges() is called. Vitest writes expected 'Count: 0' to be 'Count: 1' // Object.is equality.

Meaning: In a test, the template isn't updated right after an action. Call fixture.detectChanges() once at the start and once after every action. Since Angular 21, await fixture.whenStable() also works, but the exercise editor uses zone.js and needs detectChanges().

⚡ One click isn't enough

Write:

button.click()
button.click()
fixture.detectChanges()
expect(el.querySelector('p')?.textContent).toContain('Count: 2')

Meaning: If increment() is miswritten as this.count.set(1), a test with one click stays green. Only a two-click test catches it.

In the exercise, the editor runs your tests again on copies of counter.ts broken on purpose, for example signal(1) or c - 1. Check Count: 0 at the start and Count: 2 after two clicks.

⚡ Services and HTTP without a server

Write:

const req = httpMock.expectOne('/api/menu')
req.flush([{ id: 2, name: 'Special Egg Pancake', price: 10, stock: 6 }])

Meaning: provideHttpClientTesting() swaps the road to the server for a fake one. expectOne makes sure there's exactly one request to that URL, flush sends its fake answer, and httpMock.verify() in afterEach fails if a request went unanswered. Services come from TestBed.inject.

What you will learn