Unit-Test et Spies
Jasmine Spies
spyOn
spyOnimport { Injectable } from '@angular/core';
import { fakeAsync, flush, TestBed } from '@angular/core/testing';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class Geolocation {
getCoordinates(city): Observable<Coordinates> {
throw new NotImplementedError();
}
}
@Injectable({
providedIn: 'root'
})
export class PickyWeatherStation {
constructor(private _geolocation: Geolocation) {
}
getTemperature(city: string) {
return this._geolocation.getCoordinates(city)
.pipe(
map(coordinates => Math.round((coordinates.longitude + coordinates.latitude) / 2))
);
}
}
describe('PickyWeatherStation', () => {
let geolocation: Geolocation;
beforeEach(() => geolocation = TestBed.get(Geolocation));
let weatherStation: PickyWeatherStation;
beforeEach(() => weatherStation = TestBed.get(PickyWeatherStation));
it('should get random temperature', fakeAsync(() => {
let temperature: number;
spyOn(geolocation, 'getCoordinates').and.returnValue(of({
latitude: 45.764043,
longitude: 4.835659
}));
weatherStation.getTemperature('Lyon')
.subscribe(_temperature => temperature = _temperature);
/* Flush any async tasks. */
flush();
expect(temperature).toBe(25);
/* Check that getCoordinates has been called once with the right parameters. */
expect(geolocation.getCoordinates).toHaveBeenCalledTimes(1);
expect(geolocation.getCoordinates).toHaveBeenCalledWith('Lyon');
}));
});
Mis à jour