Simple Observable Unit Testing in Angular2

When you’re writing unit tests for your angular2 components, and you throw observables into the mix, things can get complicated fast. Some people go the more complicated route, faking responses from the actual service itself — but on the component level I feel this can get overly complicated. I prefer to test my services themselves, rather then writing fake responses with fake data for every component. In my components, I’d rather just make sure that the component is plugged into the service itself, and not let it get more complicated then that.

Thankfully there’s an easy solution for this.

You can quickly create a service stub for your data service, and then simply return an Observable.of() some test data. Here’s an example:

import { Observable } from 'rxjs/Observable'; 
import { Data, testData } from '../models';
export class DataStub {  

public get(url: string): Observable<Data[]> {
return Observable.of(testData);
  // ...

Then in your component’s spec’s beforeEach, overwrite your service that is returning an observable:

// ...
  beforeEach(async(() => {
declarations: [ MyComponent ]
}).overrideComponent(MyComponent, {
set: {
providers: [
{ provide: DataService, useClass: DataStub },
// ...

The downside of this, of course, is that we cannot easily test a server failure or error. Once again though, I prefer to handle that in my service unit tests, not the component unit tests. This only becomes a problem if you are handling errors in your component, but I prefer to use an error service that flashes error messages in a separate component rather then displaying errors in my components themselves.

Here’s a full working version: