Keeping the components lean by injecting the services into it enables us to write unit tests with a mock service. We can mock the injected service by mimicking the service behavior using its interface:
class MockTodoService extends TodoService { getPending() { return []; } }
Here, we created a mock of an existing todo service by extending and overriding the getPending method to return an empty array.
We can test this using testBed, instructing how to use the mock service, MockTodoService instead of the actual service, TodoService, as follows:
beforeEach(async(() => { TestBed.configureTestingModule({ providers: [ { provide: TodoService, useClass: MockTodoService } ]}) .compileComponents(); }));
Here, we instructed how to use MockTodoService instead of TodoService, and we can sky the outcome of testing, as follows:
it('should return empty array when getPending method is fired', () => { let service = fixture.debugElement.injector.get(TodoService); spyOn(service, 'getPending').and.returnValue([]); });
Here, it gets the mock service, MockTodoService, from fixture and adds a spyOn override to pretend that there are no pending todo items in the list.