Component Testing: Services (DRAFT) 4.0
- Component testing
- Running component tests
- Writing component tests
Components make use of services to accomplish tasks such as accessing and persisting data. You’re main choice, when testing a component that uses services, will be to decide whether or not to mock the service. This page illustrates how to do both.
Using real, locally provided services
No special measures are necessary to test
AppComponent with a
HeroService. For components under test, such locally provided
services are instatiated, as usual, thanks to Angular’s
dependency injection subsystem.
Component-external services: mock or real
Some components expect services to have been bootstrapped, or provided by an
ancestor in the app component tree. When testing such a component, you need
to supply a list of providers to the
NgTestBed before instantiating the
fixture. For example:
Note that this is true whether a real or mock service is provided. In
the following example, the providers list includes a real
HeroService but a
See Component Testing: Routing Components for details concerning the use of mock routers.
Mocking locally provided services
Mock locally provided services (to the component under test) in the same way as
for component-external services: add the requisite mock providers to the
NgTestBed before instantiating the fixture.