Unit testing a mock service
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...