Given this Angular service and its test, what will the test output?
import { TestBed } from '@angular/core/testing'; import { DataService } from './data.service'; class MockDataService { getData() { return 'mock data'; } } describe('DataService with DI', () => { let service: DataService; beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: DataService, useClass: MockDataService }] }); service = TestBed.inject(DataService); }); it('should return mock data', () => { expect(service.getData()).toBe('mock data'); }); });
Think about how dependency injection replaces the real service with the mock.
The TestBed configuration replaces the real DataService with MockDataService. So when injected, the service is the mock, and getData returns 'mock data'.
Consider this test setup for a service that uses HttpClient. Why does it fail?
import { TestBed } from '@angular/core/testing'; import { HttpClientModule } from '@angular/common/http'; import { ApiService } from './api.service'; describe('ApiService', () => { let service: ApiService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientModule], providers: [ApiService] }); service = TestBed.inject(ApiService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
HttpClient needs a module to provide it in Angular tests.
HttpClient is provided by HttpClientModule. Without importing it in TestBed.configureTestingModule imports, the provider is missing, causing the error.
Choose the correct way to inject a mocked LoggerService in an Angular test.
class MockLoggerService { log(message: string) { return 'mock log: ' + message; } } beforeEach(() => { TestBed.configureTestingModule({ // What goes here? }); const logger = TestBed.inject(LoggerService); });
Remember to provide the original service token and specify the mock class.
To replace LoggerService with a mock, provide LoggerService token with useClass set to MockLoggerService.
Given this test with dependency injection, what is the value of result after service.getValue() is called?
class RealService { getValue() { return 42; } } class FakeService { getValue() { return 100; } } let result: number; beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: RealService, useClass: FakeService }] }); const service = TestBed.inject(RealService); result = service.getValue(); });
Check which class is actually injected for RealService.
The provider replaces RealService with FakeService, so getValue returns 100.
Choose the most accurate description of how Angular's dependency injection works in service testing.
Think about how TestBed providers affect injected services.
Angular's DI system allows replacing services with mocks or alternatives by configuring providers in TestBed during tests.