Mocking Angular 2 service calls with Observables in component unit tests

Unit Testing Angular 2 Component service calls

Posted on February 4, 2017

When unit testing your Angular 2 modules you’ll need to mock out any service calls.

I had a number of issues where my unit tests passed locally but failed when they were run on Jenkins with the error “ERROR Response with status: 0 for URL: null“. This was down to the module trying to connect to the api, which you don’t want when unit testing.

Mocking out all my service calls solved this issue. Here’s how I did it:

1) Import your service.

import {MyService} from './my-service.service';

2) Import Observable from rxjs.

import {Observable} from 'rxjs/Observable';

Add your service to the providers array and swap it out for a mock service class.

		{provide: MyService, useClass : mockService }

3) It’s then just a case of creating the mockService class, creating methods that mirror your service methods and then returning the data/observable.

class mockService {
	get () {
		return Observable.of({test: "data"});

You can obviously swap out {test: “data”} for whatever data you want to return.