'How to test ng-web-apis/geolocation Observable in angular 8?
I'm trying to test a simple angular 8 service that gets user location using GeoLocation Service from Web APIs for Angular
public enableGPS() {
if (!this.locationSubscription)
this.locationSubscription = this.geoLocationService.subscribe(
(position) => {
this._currentLocation = position.coords;
}
);
}
And this is the test
describe("Toggle Location Service", () => {
it("should enable location service", () => {
const testPosition = {
position: {
coords: {
longitude: 1.0,
latitude: 2.0
}
}};
let geoLocationService: GeolocationService = TestBed.get(GeolocationService);
spyOn(geoLocationService, 'subscribe').and.returnValue(
Observable.of(testPosition));
service.enableGPS();
expect(service.currentLocation).toEqual(testPosition);
});
});
but service.currentLocation is always undefined and the subscription callback is never called
Solution 1:[1]
I don't know if it's too late to answer your question, but I just found myself needing to use this in my project.
Well, not to make it any longer and the solution remains because I couldn't make the library work, so use the browser's resources directly.
https://developer.mozilla.org/en/docs/Web/API/Geolocation/getCurrentPosition
I created a service that would be the following:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LocationService{
constructor(){
}
getPosition(): Promise<any> {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resp => {
resolve({lng: resp.coords.longitude, lat: resp.coords.latitude});
},
err => {
reject(err);
});
});
}
}
Then I call it in my component:
import { LocationService } from '../Interfaces/Services/location.service';
location : any = { latitude: '', longitude: '' };
constructor(
private _locationService: LocationService
) {
}
async getLocation() {
this._locationService.getPosition().then(pos => {
this.location= {
latitude: pos.lat,
longitude: pos.lng
}
});
}
I hope it helps you and if not, I hope the answer is clear for future developers
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |