What We're Building On

This is the second installment in our testing-in-isolation series. While child components represent one kind of dependency you'll encounter in a component, injected services are another dependency type that needs mocking during unit testing.

Angular is built around dependency injection, and services let us extract logic into reusable classes shared across components or other services.

Setting Up a Service

Generate a new service with the Angular CLI by running ng g s employees. This creates an EmployeesService and places it in your project's app directory.

Continuing from the previous article, open the AppComponent, add a constructor, and inject the EmpoyeesService.

constructor(private employeesService: EmployeesService) {}
Enter fullscreen mode Exit fullscreen mode

Since EmployeesService has no functions and the AppComponent doesn't call anything from it, the existing tests still pass. But it's good practice to mock services as soon as you inject them into a component.

Mocking the Service

Open app.component.spec.ts. Near the top of the file, alongside the mock HeaderComponent from the previous article, add a new class to serve as the mock for EmployeesService.

class MockEmployeesService {}
Enter fullscreen mode Exit fullscreen mode

With the mock class in place, we need to configure the test environment to use it instead of the actual EmployeesService.

The TestBed.configureTestingModule currently only has a declarations array. Add a providers array containing an object, as shown below.

TestBed.configureTestingModule({
      declarations: [
        ...
      ],
      providers: [{provide: EmployeesService, useClass: MockEmployeesService}]
    }).compileComponents();
Enter fullscreen mode Exit fullscreen mode

What's happening here?

When the AppComponent tests run, we're telling the test harness that the component needs the EmployeeService. Rather than using the real service, we explicitly point it to the mock class defined above. This lets us test the AppComponent in true isolation.

Wrapping Up

Good work—you now know how to mock both components and services. In the next article, we'll start writing actual tests for the Angular project.

Enjoyed this post? Check out my other articles, subscribe to my newsletter, and follow me on Twitter!