O'Reilly logo

Learning Angular for .NET Developers by Rajesh Gunasundaram

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required