Testing — Angular Technical Interview Questions & Answers

Testing

Testing

  • Unit test a component with TestBed. Configure declarations/imports, create fixture, detectChanges, query the native element. Expect ‘Fail’ text when marks are 20.
  • HttpClientTestingModule (or provideHttpClientTesting) mocks HTTP. Don’t hit a real server in unit tests. Trap: only writing e2e and skipping TestBed.

Technical Interview Tip: TestBed fixture + one assertion on Fail.

Code Examples for Testing

Testing — working example

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  template: `
    <h1>{{ title }}</h1>
    <button (click)="toggle()">Toggle</button>
    <p *ngIf="open">Panel open</p>
  `,
})
export class AppComponent {
  title = "Angular practice";
  open = true;
  toggle() {
    this.open = !this.open;
  }
}

Testing: toggle open. Say whether the panel is on screen after one click.

How to Explain Testing to an Interviewer

How do you unit-test a component?

TestBed detectChanges query text