Blog

Part 24 · Testing Angular Components with Vitest and TestBed

Write your first Angular component tests. This part covers ng test with Vitest, TestBed and the fixture, clicking and waiting with whenStable, setting inputs, checking outputs, and swapping in a fake service.

So far we’ve checked our pages by clicking around in a browser. That works once. It doesn’t tell you, a month later, that a change in one component broke another. A test is a small program that does the clicking for you and checks the result, every time you run it.

This part covers ng test, spec files, describe, it and expect, TestBed and the fixture it gives you, clicking a button and waiting for Angular, setting inputs, checking outputs, and giving a component a fake service, as Part 13 promised. In Part 1 you deleted app.spec.ts, so your project has no tests yet. We’ll add the first one. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published, and each test run with ng test.

Try this first

Make a small counter component in src/app/counter.ts:

// src/app/counter.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="add()">Add one</button>
  `,
})
export class Counter {
  protected readonly count = signal(0);

  protected add() {
    this.count.update((n) => n + 1);
  }
}

and show it from src/app/app.ts:

// src/app/app.ts
import { Component } from '@angular/core';
import { Counter } from './counter';

@Component({
  selector: 'app-root',
  imports: [Counter],
  template: `<app-counter />`,
})
export class App {}

The page shows:

Count: 0
Add one

Now add a test next to it, in src/app/counter.spec.ts. It makes a Counter and checks that it says “Count: 0”:

// src/app/counter.spec.ts
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  it('starts at 0', () => {
    const fixture = TestBed.createComponent(Counter);
    const el: HTMLElement = fixture.nativeElement;
    expect(el.textContent).toContain('Count: 0');
  });
});

Stop ng serve (or open a second terminal) and run the tests once:

ng test --watch=false

Before you read on, guess. The page says “Count: 0”. Does the test pass?

It fails. These lines are from the output:

src/app/counter.spec.ts > Counter > starts at 0
AssertionError: expected 'Add one' to contain 'Count: 0'
...
Tests  1 failed (1)

The component’s text was Add one. The button is there, but the “Count: 0” line is missing. By the end of the next few sections you’ll know why, and the line that fixes it.

What ng test does

ng test finds every file in src whose name ends in .spec.ts (or .test.ts), builds them with the Angular compiler, and runs them with Vitest, a test runner. A new Angular 22 project is set up for Vitest already. You can see it in angular.json, where the test target uses @angular/build:unit-test, and in package.json, which lists vitest.

The tests don’t run in a real browser. They run in Node.js, with jsdom: a library that builds a fake page in memory, with document, elements, click() and textContent. It doesn’t lay anything out or paint anything, so a test can’t check sizes, positions or colours. For checking text, clicks and inputs, it behaves like a browser, and it’s fast. (ng test uses happy-dom, a similar library, if you install it. A new project has jsdom.)

In a terminal, ng test on its own keeps running. It runs the tests, then watches your files and runs them again each time you save. Press q to stop it. ng test --watch=false runs them once and stops, which is handy for the examples here. If there are no spec files at all, it stops with this:

Error: No tests found matching the following patterns:
- Included: **/*.spec.ts, **/*.test.ts

That’s the message Part 1 said you’d see. Now we have a spec file.

A spec file sits next to the file it tests, with the same name plus .spec: counter.ts and counter.spec.ts. That’s what ng generate component does too, and it makes the test easy to find.

describe, it and expect

Here’s the test again, piece by piece:

describe('Counter', () => {
  it('starts at 0', () => {
    expect(el.textContent).toContain('Count: 0');
  });
});
  • describe('Counter', ...) groups tests under a name. You usually have one describe per spec file, named after the class it tests.
  • it('starts at 0', ...) is one test. The name should read as a sentence: “it starts at 0”. When the test fails, that name is what you see.
  • expect(value) starts a check. .toContain('Count: 0') passes if the value contains that text. Others you’ll use: .toBe(x) (exactly equal, the same check as Object.is from Part 3), .toEqual(x) (same contents, for arrays and objects), .toBeTruthy(), and .toHaveBeenCalledWith(x), which we’ll meet with outputs.

You don’t import describe, it or expect. Vitest provides them as globals, and tsconfig.spec.json tells TypeScript about them with "types": ["vitest/globals"].

A test passes if it finishes without a failed expect and without throwing an error. The first failed expect stops that test, and Vitest moves on to the next one.

TestBed and the fixture

TestBed is Angular’s testing helper, from @angular/core/testing. It sets up a small Angular app for each test, with its own injector. TestBed.createComponent(Counter) makes a Counter in that app and hands back a fixture: an object that holds the component and lets you look at it. You’ll use three things on it:

  • fixture.nativeElement is the component’s element in the DOM. You read its textContent and find things in it with querySelector, as in any web page. Its type is any, so we write const el: HTMLElement = fixture.nativeElement to get help from TypeScript. In a test that element is a <div>, not <app-counter>.
  • fixture.componentInstance is the Counter object itself, the instance of your class.
  • fixture.componentRef lets you set inputs, as you’ll see below.

The test that ng new writes, and much code you’ll read, starts with one more step:

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

beforeEach runs before every it in the describe. configureTestingModule sets up the test app. imports: [Counter] makes Counter available to it, and compileComponents() compiles templates that aren’t compiled yet. With a standalone component and ng test, you can skip both: createComponent sets the component up by itself, and the CLI has already compiled the templates. Every test in this part does that. You still need configureTestingModule for providers, which we’ll use for a fake service.

TestBed throws its test app away after each it, so tests don’t see each other’s components or services.

Here’s how the pieces fit together:

counter.spec.ts 1. createComponent(Counter) 2. await whenStable() 3. button.click() 4. await whenStable() 5. expect(p.textContent) fixture componentInstance componentRef nativeElement Counter count: 1 render (click) DOM (jsdom) Count: 1 Add one click() The test acts on the DOM and waits. Angular renders as it does in the app.

The test reaches the component through the fixture: the class with componentInstance, the page with nativeElement.

Waiting for Angular: whenStable

Now to the missing text. In Part 3 we saw that Angular doesn’t redraw the moment something changes. It marks the component and schedules a render for when your code has finished. createComponent works the same way. It builds the elements from the template straight away: the <p> and the <button> with its fixed text “Add one”. The values in double curly braces are filled in by the first render, and that’s only scheduled. When we printed the component’s HTML straight after createComponent, it was <p></p><button>Add one</button>. Our test read textContent on the very next line, before the render ran.

The fix is to wait:

// src/app/counter.spec.ts
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  it('starts at 0', async () => {
    const fixture = TestBed.createComponent(Counter);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;
    expect(el.textContent).toContain('Count: 0');
  });
});

Now the test passes:

Test Files  1 passed (1)
Tests  1 passed (1)

Two things changed:

  • fixture.whenStable() returns a promise: a value that will be ready later. It’s ready when Angular has nothing left to do, including any render it scheduled.
  • await waits for a promise. You can only use it inside an async function, so the test’s function became async () => { ... }. Vitest waits for an async test to finish.

You’ll also see fixture.detectChanges() in many tests. It runs change detection right now, with no waiting. In our runs, both made the text appear. Prefer await fixture.whenStable(): it lets Angular render the way it does in the app, and it also waits for other work Angular is tracking. One exception: while a request is waiting for an answer, whenStable() waits too. Part 25 shows what to do then. Older tests call detectChanges() after every change (see “In older code” below).

Clicking a button

To click, find the button in the DOM and call its click() method. Then wait again, and check the text:

// src/app/counter.spec.ts
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  it('starts at 0', async () => {
    const fixture = TestBed.createComponent(Counter);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;
    expect(el.textContent).toContain('Count: 0');
  });

  it('adds one when you click Add one', async () => {
    const fixture = TestBed.createComponent(Counter);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;

    el.querySelector('button')!.click();
    await fixture.whenStable();

    expect(el.querySelector('p')!.textContent).toBe('Count: 1');
  });
});
Test Files  1 passed (1)
Tests  2 passed (2)

el.querySelector('button') finds the first <button> inside the component. It returns HTMLButtonElement | null, because there might not be one. The ! after it is TypeScript for “I know this isn’t null”. If the button were missing, the test would fail with a TypeError on that line, which is a fine way to find out.

The click calls add(), which sets the signal to 1, just like a real click. But the screen doesn’t change at once. When we printed textContent straight after click(), it still said Count: 0. The render comes later, and await fixture.whenStable() waits for it. Click, wait, check: that’s the rhythm of every component test.

The check uses toBe on the <p>‘s text, not toContain on the whole component. Checking one element exactly catches more mistakes. “Count: 10” contains “Count: 1”, but it isn’t “Count: 1”.

Inputs and outputs

Let’s give the counter a step input (how much each click adds) and a changed output that sends the new count, as in Part 5 and Part 6:

// src/app/counter.ts
import { Component, input, output, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="add()">Add {{ step() }}</button>
  `,
})
export class Counter {
  readonly step = input(1);
  readonly changed = output<number>();
  protected readonly count = signal(0);

  protected add() {
    this.count.update((n) => n + this.step());
    this.changed.emit(this.count());
  }
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Counter } from './counter';

@Component({
  selector: 'app-root',
  imports: [Counter],
  template: `<app-counter [step]="5" />`,
})
export class App {}

Click Add 5 twice. The page shows:

Count: 10
Add 5

In a test there’s no parent template to write [step]="5". Instead, fixture.componentRef.setInput('step', 5) sets the input, the way a parent’s binding would. For the output, we listen with subscribe, and record what it sends with vi.fn():

// src/app/counter.spec.ts
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  it('adds 1 by default', async () => {
    const fixture = TestBed.createComponent(Counter);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;

    el.querySelector('button')!.click();
    await fixture.whenStable();

    expect(el.querySelector('p')!.textContent).toBe('Count: 1');
  });

  it('adds the step it is given', async () => {
    const fixture = TestBed.createComponent(Counter);
    fixture.componentRef.setInput('step', 5);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;
    expect(el.querySelector('button')!.textContent).toBe('Add 5');

    el.querySelector('button')!.click();
    await fixture.whenStable();

    expect(el.querySelector('p')!.textContent).toBe('Count: 5');
  });

  it('sends the new count', async () => {
    const fixture = TestBed.createComponent(Counter);
    const changed = vi.fn();
    fixture.componentInstance.changed.subscribe(changed);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;

    el.querySelector('button')!.click();
    el.querySelector('button')!.click();

    expect(changed).toHaveBeenCalledTimes(2);
    expect(changed).toHaveBeenLastCalledWith(2);
  });
});
Test Files  1 passed (1)
Tests  3 passed (3)

A few things to notice:

  • setInput('step', 5) takes the input’s name as a string. Like any change, it shows on the screen after a render, so we set it before whenStable(). When we set it after the first render and read the text without waiting, the button still said Add 1.
  • vi.fn() makes a mock function, also called a spy. It does nothing, but it remembers every call and its arguments. vi is another Vitest global. toHaveBeenCalledTimes(2) and toHaveBeenLastCalledWith(2) check what it remembered.
  • The output test doesn’t wait after the clicks. emit calls the listener straight away, inside add(). Only the screen waits for a render.
  • changed is readonly and public, so the test can reach it through componentInstance. count is protected, so it can’t, and that’s good: the test checks what a user sees, the text, not the component’s insides.

Binding inputs and outputs when you create the component

createComponent can also take the bindings up front, like a parent template would. inputBinding and outputBinding come from @angular/core:

// src/app/counter.spec.ts
import { inputBinding, outputBinding, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  it('follows its step input', async () => {
    const step = signal(2);
    const changed = vi.fn();
    const fixture = TestBed.createComponent(Counter, {
      bindings: [inputBinding('step', step), outputBinding('changed', changed)],
    });
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;

    el.querySelector('button')!.click();
    step.set(10);
    await fixture.whenStable();
    el.querySelector('button')!.click();
    await fixture.whenStable();

    expect(el.querySelector('p')!.textContent).toBe('Count: 12');
    expect(changed).toHaveBeenCalledWith(2);
    expect(changed).toHaveBeenLastCalledWith(12);
  });
});
Test Files  1 passed (1)
Tests  1 passed (1)

inputBinding('step', step) binds the input to a signal. When the test changes step, the input follows, just as [step]="step()" would in a parent. outputBinding('changed', changed) is (changed)="changed($event)". Use whichever reads better. setInput is short for one fixed value; inputBinding is handy when the value changes during the test.

Worked example: a fake service

Part 13 said that because a component asks for its services with inject(), a test can hand it a fake one. Here’s where that pays off.

This greeting depends on the time of day. It gets the hour from a Clock service:

// src/app/clock.ts
import { Service } from '@angular/core';

@Service()
export class Clock {
  hour() {
    return new Date().getHours();
  }
}
// src/app/greeting.ts
import { Component, inject } from '@angular/core';
import { Clock } from './clock';

@Component({
  selector: 'app-greeting',
  template: `<p>{{ message }}</p>`,
})
export class Greeting {
  private readonly clock = inject(Clock);
  protected readonly message = this.clock.hour() < 12 ? 'Good morning' : 'Good afternoon';
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Greeting } from './greeting';

@Component({
  selector: 'app-root',
  imports: [Greeting],
  template: `<app-greeting />`,
})
export class App {}

message is a plain field, worked out once when the component is made. It never changes, so it doesn’t need to be a signal.

What does the page show? It depends on when you look. That’s the problem. A test that uses the real Clock would pass in the morning and fail after lunch. We want to choose the hour.

TestBed.configureTestingModule({ providers: [...] }) adds providers to the test app, like providers in app.config.ts. { provide: Clock, useValue: fakeClock } from Part 14 says “when someone asks for Clock, give them this object”. The component’s inject(Clock) gets our fake, and never knows:

// src/app/greeting.spec.ts
import { TestBed } from '@angular/core/testing';
import { Clock } from './clock';
import { Greeting } from './greeting';

describe('Greeting', () => {
  function createAt(hour: number) {
    const fakeClock: Clock = { hour: () => hour };
    TestBed.configureTestingModule({
      providers: [{ provide: Clock, useValue: fakeClock }],
    });
    return TestBed.createComponent(Greeting);
  }

  it('says good morning at 9', async () => {
    const fixture = createAt(9);
    await fixture.whenStable();
    expect(fixture.nativeElement.textContent).toBe('Good morning');
  });

  it('says good afternoon at 12', async () => {
    const fixture = createAt(12);
    await fixture.whenStable();
    expect(fixture.nativeElement.textContent).toBe('Good afternoon');
  });
});
Test Files  1 passed (1)
Tests  2 passed (2)

Some things to notice:

  • const fakeClock: Clock = { hour: () => hour } is a plain object. The type annotation : Clock makes TypeScript check that it has everything a Clock has. If someone later adds a method to Clock and the component starts calling it, this line stops building, and you know the fake needs it too.
  • configureTestingModule has to come before createComponent. Once a component is made, the test app is set up, and TestBed refuses to change it.
  • The helper createAt is a normal function inside describe. Repeated setup in a small function keeps each it short and about one thing.
  • The second test checks 12, not 15. The < 12 is where a mistake would hide, so that’s the hour worth testing.

The fake replaces the service the component would find in the root injector. That’s why it works for @Service() classes and for anything in app.config.ts. It doesn’t work if the component lists the service in its own providers. As Part 13 showed, a component’s own providers are found first. We tried it: with providers: [Clock] on Greeting and the fake set to 9, the test said “Good afternoon”. It got the real clock, and we ran it after noon. For that case, TestBed.overrideComponent(Greeting, { set: { providers: [...] } }) replaces the component’s own providers.

Worked example: a failing test, and reading it

Tests earn their keep when they fail. Here’s a vote button. Each click on Up adds one, and the voted output tells the parent the new score:

// src/app/vote.ts
import { Component, output, signal } from '@angular/core';

@Component({
  selector: 'app-vote',
  template: `
    <button (click)="up()">Up</button>
    <span>{{ score() }}</span>
  `,
})
export class Vote {
  readonly voted = output<number>();
  protected readonly score = signal(0);

  protected up() {
    this.voted.emit(this.score());
    this.score.update((n) => n + 1);
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Vote } from './vote';

@Component({
  selector: 'app-root',
  imports: [Vote],
  template: `
    <app-vote (voted)="last.set($event)" />
    <p>Parent heard: {{ last() }}</p>
  `,
})
export class App {
  protected readonly last = signal(0);
}

Click Up. The page shows:

Up1
Parent heard: 0

(The button and the number run together, Up1, because they sit on one line and the page text joins them.)

Look closely, and the bug is already there: the score says 1, and the parent heard 0. It’s easy to miss in a browser. Here’s a test that says what we expect:

// src/app/vote.spec.ts
import { TestBed } from '@angular/core/testing';
import { Vote } from './vote';

describe('Vote', () => {
  it('sends the new score', async () => {
    const fixture = TestBed.createComponent(Vote);
    const voted = vi.fn();
    fixture.componentInstance.voted.subscribe(voted);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;

    el.querySelector('button')!.click();
    await fixture.whenStable();

    expect(el.querySelector('span')!.textContent).toBe('1');
    expect(voted).toHaveBeenCalledWith(1);
  });
});

ng test --watch=false prints a summary that counts the failures, and a report for each failed test. Here are the lines that matter, with ... where we skipped some:

src/app/vote.spec.ts > Vote > sends the new score
AssertionError: expected "vi.fn()" to be called with arguments: [ 1 ]
...
1st vi.fn() call:
...
Number of calls: 1
...
❯ src/app/vote.spec.ts:17:19
...
17|     expect(voted).toHaveBeenCalledWith(1);
...
Test Files  1 failed (1)
Tests  1 failed (1)

Read the report from the top:

  • src/app/vote.spec.ts > Vote > sends the new score is the file, the describe and the it. Your line starts with FAIL and your project’s name, practice, shown as a coloured label. This is why test names should read as sentences.
  • expected "vi.fn()" to be called with arguments: [ 1 ] is the check that failed, in words. Our spy is called vi.fn() in messages.
  • Under 1st vi.fn() call: come two short lines we skipped: - 1, is what we expected and + 0, is what it got. The first (and only) call sent 0, not 1. Number of calls: 1 says it was called once, so the output did fire, with the wrong value.
  • src/app/vote.spec.ts:17:19 is the file, line and column of the failed expect, and the code under it marks the spot.
  • The span check on line 16 passed. A failed expect stops the test, so if the screen had been wrong, we’d have seen that failure first.

Now decide: is the test wrong, or the code? The test says “after one click, the parent hears 1”, which is what we want. So the code is wrong. up() emits the score, then adds one. It sends the old value. Swap the two lines:

// src/app/vote.ts
import { Component, output, signal } from '@angular/core';

@Component({
  selector: 'app-vote',
  template: `
    <button (click)="up()">Up</button>
    <span>{{ score() }}</span>
  `,
})
export class Vote {
  readonly voted = output<number>();
  protected readonly score = signal(0);

  protected up() {
    this.score.update((n) => n + 1);
    this.voted.emit(this.score());
  }
}
Test Files  1 passed (1)
Tests  1 passed (1)

The test stays. If someone moves those lines back next year, it fails again, with the same clear message. That’s the real reason to write it.

One habit worth building: when you write a new test, break the code on purpose for a moment and watch the test fail. A test that never fails might not be checking anything.

In older code

Projects made before Angular 21 use Karma and Jasmine instead of Vitest, and ng test opened a real Chrome window. The tests look almost the same. The differences you’ll notice: jasmine.createSpy() where we write vi.fn(), and spyOn(obj, 'method') where Vitest has vi.spyOn. Older tests also call fixture.detectChanges() after every change, and wrap tests in fakeAsync(() => { ... tick(); }) or waitForAsync. Those need zone.js. Angular’s API notes for fakeAsync say it can’t be used with the Vitest runner. You’ll also see declarations: [Counter] in configureTestingModule for components that belong to an NgModule, and fixture.debugElement.query(By.css('button')) where we use nativeElement.querySelector('button').

Best practices

  • Click, wait, check. Act on the DOM, await fixture.whenStable(), then expect. It replaces calling fixture.detectChanges() after every line, and lets Angular render as it does in the app.
  • Test what the user sees. Query the DOM and check its text, and check outputs with a spy. Leave protected members alone. A test that reads the DOM still passes when you rename a field, and fails when the page is wrong.
  • Put the spec file next to the component. counter.ts and counter.spec.ts side by side are easy to find and easy to move together.
  • Fake services, not components. Give useValue a typed fake (const fake: Clock = ...) for anything slow, random or time-based. TypeScript then tells you when the fake falls behind the real service.
  • Name each it as a sentence about behaviour. “sends the new score” tells you what broke before you open the file. “test 3” doesn’t.

Tips and traps

  • Reading the DOM before the first render. The fixed text is there, but every double-curly-brace value is missing, as in expected 'Add one' to contain 'Count: 0'. Add await fixture.whenStable() after createComponent, and make the test async.
  • Forgetting await. fixture.whenStable(); without await doesn’t wait, so the check sees the old text. Nothing warns you. Check that each whenStable() has await in front of it.
  • A typo in setInput. setInput('stepp', 5) doesn’t fail the test. Angular only logs NG0303: Can't set value of the 'stepp' input on the '_Counter' component, and ng test prints it in a stderr | block above the results. The test is still marked passed, so read the whole output, not just the last two lines.
  • The fake is ignored. If the component lists the service in its own providers, the test’s configureTestingModule providers lose. The test uses the real service and may pass or fail depending on, say, the time of day. Use TestBed.overrideComponent.
  • configureTestingModule after createComponent. The test fails with Cannot configure the test module when the test module has already been instantiated. Configure first, then create.
  • Expecting a real browser. jsdom has no layout, so sizes and positions are all 0. Test text, attributes and events in component tests, and look at the page for the rest.

A component test does what a user would do, waits for Angular to render, and checks what a user would see.

Exercises

Exercise 1. This test for the fixed Vote fails. Read the output and say why, then fix the test (not the component).

// src/app/vote.spec.ts
import { TestBed } from '@angular/core/testing';
import { Vote } from './vote';

describe('Vote', () => {
  it('shows 2 after two clicks', async () => {
    const fixture = TestBed.createComponent(Vote);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;
    const button = el.querySelector('button')!;

    button.click();
    button.click();
    fixture.whenStable();

    expect(el.querySelector('span')!.textContent).toBe('2');
  });
});
AssertionError: expected '0' to be '2' // Object.is equality
...
Tests  1 failed (1)

Exercise 2. Write a spec for the first Counter (the one with Add one and no input). It should click Add one three times and check that the page says Count: 3. Do you need to wait after every click?

Exercise 3. Change Greeting so it takes a required name input and shows Good morning, Ana. Then write a test that uses the fake clock at 8 and the name Ana. Hint: set a required input before the first whenStable().

Answers

1. The span still said 0. Both clicks worked, but fixture.whenStable() has no await in front of it, so the test didn’t wait for the render. It checked the old text. Add the await:

// src/app/vote.spec.ts
import { TestBed } from '@angular/core/testing';
import { Vote } from './vote';

describe('Vote', () => {
  it('shows 2 after two clicks', async () => {
    const fixture = TestBed.createComponent(Vote);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;
    const button = el.querySelector('button')!;

    button.click();
    button.click();
    await fixture.whenStable();

    expect(el.querySelector('span')!.textContent).toBe('2');
  });
});
Test Files  1 passed (1)
Tests  1 passed (1)

2. No. Each click changes the signal at once. Only the screen waits, and one whenStable() at the end renders the final count. Here are the counter, the spec and the app.ts that shows it:

// src/app/counter.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="add()">Add one</button>
  `,
})
export class Counter {
  protected readonly count = signal(0);

  protected add() {
    this.count.update((n) => n + 1);
  }
}
// src/app/counter.spec.ts
import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  it('counts three clicks', async () => {
    const fixture = TestBed.createComponent(Counter);
    await fixture.whenStable();
    const el: HTMLElement = fixture.nativeElement;
    const button = el.querySelector('button')!;

    button.click();
    button.click();
    button.click();
    await fixture.whenStable();

    expect(el.querySelector('p')!.textContent).toBe('Count: 3');
  });
});
// src/app/app.ts
import { Component } from '@angular/core';
import { Counter } from './counter';

@Component({
  selector: 'app-root',
  imports: [Counter],
  template: `<app-counter />`,
})
export class App {}
Test Files  1 passed (1)
Tests  1 passed (1)

3. input.required<string>() from Part 5 for the name, and setInput('name', 'Ana') before the first render:

// src/app/clock.ts
import { Service } from '@angular/core';

@Service()
export class Clock {
  hour() {
    return new Date().getHours();
  }
}
// src/app/greeting.ts
import { Component, computed, inject, input } from '@angular/core';
import { Clock } from './clock';

@Component({
  selector: 'app-greeting',
  template: `<p>{{ message() }}</p>`,
})
export class Greeting {
  readonly name = input.required<string>();
  private readonly clock = inject(Clock);
  protected readonly message = computed(() => {
    const part = this.clock.hour() < 12 ? 'Good morning' : 'Good afternoon';
    return `${part}, ${this.name()}`;
  });
}
// src/app/greeting.spec.ts
import { TestBed } from '@angular/core/testing';
import { Clock } from './clock';
import { Greeting } from './greeting';

describe('Greeting', () => {
  it('greets Ana in the morning', async () => {
    const fakeClock: Clock = { hour: () => 8 };
    TestBed.configureTestingModule({
      providers: [{ provide: Clock, useValue: fakeClock }],
    });
    const fixture = TestBed.createComponent(Greeting);
    fixture.componentRef.setInput('name', 'Ana');
    await fixture.whenStable();
    expect(fixture.nativeElement.textContent).toBe('Good morning, Ana');
  });
});
// src/app/app.ts
import { Component } from '@angular/core';
import { Greeting } from './greeting';

@Component({
  selector: 'app-root',
  imports: [Greeting],
  template: `<app-greeting name="Ana" />`,
})
export class App {}
Test Files  1 passed (1)
Tests  1 passed (1)

message is now a computed, because it reads the name input, and inputs are signals. In the app, name="Ana" sets the input to the text “Ana”.

What’s next

Components are half of an app. In Part 25, we’ll test services on their own, fake the server with HttpTestingController, and test routes with RouterTestingHarness.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.