Complete the code to inject a service into a component constructor.
constructor(private [1]: DataService) {}The service instance is usually named in camelCase in the constructor to be used inside the component.
Complete the code to provide a mock service for testing.
providers: [{ provide: DataService, useClass: [1] }]In tests, we replace the real service with a mock class to control behavior.
Fix the error in injecting a service in the test setup.
beforeEach(() => {
TestBed.configureTestingModule({
providers: [[1]]
});
});To replace a service with a mock in tests, use the provide object with useClass.
Fill both blanks to inject and use a mock service in a test.
let service: DataService;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{ provide: [1], useClass: [2] }]
});
service = TestBed.inject(DataService);
});We provide DataService token and replace it with MockDataService class for testing.
Fill all three blanks to create a test that uses dependency injection to replace a service and verify a method call.
describe('MyComponent', () => { let service: [1]; beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: [2], useClass: [3] }] }); service = TestBed.inject(DataService); }); it('should call fetchData', () => { spyOn(service, 'fetchData').and.returnValue(of([])); service.fetchData(); expect(service.fetchData).toHaveBeenCalled(); }); });
The test replaces DataService with MockDataService and spies on fetchData to check it was called.