The next example outlines how to test services. We want to test a service, which returns some countries from a remote backend:
@Injectable()
export class CountryService {
constructor(private http: Http) { }
getCountries(): Observable<Country[]> {
return this.http.get('/assets/data/countries.json')
.map(response => response.json().data as Country[]);
}
}
The Country objects have the following shape:
interface Country {
name: any;
dial_code?: any;
code?: any;
}
We don't want to make HTTP calls during the tests. To achieve that, we have to replace XHRBackend by MockBackend. The MockBackend allows us to catch outgoing HTTP requests and simulate incoming responses. We can just define a response as we want and then compare the result from the service with our expectations. The next code snippet shows how to build a mocked response, so when we finally make a call to our service, it gets the predefined array of countries:
import {TestBed, inject...