mediumFrontend

Explain how to perform unit testing on components with Signals using TestBed.

1.1k views
01

Understand the problem

Describe testing strategies for signal-based components.

testingsignals
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Unit test for a signal-based calculator component
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { signal, Component, computed } from '@angular/core';

@Component({
  selector: 'app-calc',
  template: '<span id="total">{{ total() }}</span>'
})
class CalcComponent {
  x = signal(10);
  y = signal(20);
  total = computed(() => this.x() + this.y());
}

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

  beforeEach(() => {
    fixture = TestBed.createComponent(CalcComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should calculate computed totals reactively', () => {
    expect(component.total()).toBe(30);

    component.x.set(100);
    fixture.detectChanges();

    const text = fixture.nativeElement.querySelector('#total').textContent;
    expect(text).toBe('120');
  });
});
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.