element after fixture.detectChanges()?
import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Component({ selector: 'app-greet', template: `<p>{{ greeting }}</p>` }) class GreetComponent { greeting = 'Hello, Angular!'; } beforeEach(() => { TestBed.configureTestingModule({ declarations: [GreetComponent] }); }); const fixture = TestBed.createComponent(GreetComponent); fixture.detectChanges(); const pElement = fixture.nativeElement.querySelector('p'); const text = pElement.textContent;
The component's greeting property is set to 'Hello, Angular!'. After fixture.detectChanges(), Angular updates the template, so the
element shows this text.
import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Component({ selector: 'app-my', template: `<div>Test</div>` }) class MyComponent {} // TestBed configurations: // A: declarations: [MyComponent] // B: imports: [MyComponent] // C: providers: [MyComponent] // D: declarations: []
Option A does not declare MyComponent. So, TestBed.createComponent(MyComponent) throws an error because Angular doesn't know about this component in the testing module.
import { Injectable } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Injectable() class DataService { getData() { return 'data'; } } beforeEach(() => { TestBed.configureTestingModule({ declarations: [], providers: [] }); }); const service = TestBed.inject(DataService);
The error occurs because DataService is not provided in the testing module's providers array. Angular cannot inject a service it doesn't know about.
component.count after fixture.detectChanges()?import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Component({ selector: 'app-counter', template: `<button (click)="increment()">Increment</button><p>{{ count }}</p>` }) class CounterComponent { count = 0; increment() { this.count++; } } beforeEach(() => { TestBed.configureTestingModule({ declarations: [CounterComponent] }); }); const fixture = TestBed.createComponent(CounterComponent); const component = fixture.componentInstance; component.increment(); fixture.detectChanges();
The increment() method is called once before fixture.detectChanges(), so count becomes 1.
ApiService. You want to test the component with a mock service that returns fixed data. Which TestBed configuration correctly provides the mock?class ApiService { fetch() { return 'real data'; } } class MockApiService { fetch() { return 'mock data'; } } TestBed.configureTestingModule({ declarations: [MyComponent], // Which providers array is correct? providers: ??? });
Option D tells Angular to provide ApiService using the MockApiService class, effectively replacing the real service with the mock during testing.
