Nic*_*tti 11 javascript unit-testing geolocation jasmine
我有一个调用geolocator的函数,我不知道如何测试这个函数.我试过监视地理定位器并返回假数据但没有成功,原来的功能仍然使用,所以我不得不等待,我不能使用模拟数据.
// this doesn't work
var navigator_spy = spyOn( navigator.geolocation, 'getCurrentPosition' ).andReturn( {
coords : {
latitude : 63,
longitude : 143
}
} );
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
Wil*_*ams 19
当您调用地理位置代码时,它看起来像这样:
navigator.geolocation.getCurrentPosition(onSuccess, onError);
Run Code Online (Sandbox Code Playgroud)
这意味着你正在调用它并传递它的功能:
function onSuccess(position) {
// do something with the coordinates returned
var myLat = position.coords.latitude;
var myLon = position.coords.longitude;
}
function onError(error) {
// do something when an error occurs
}
Run Code Online (Sandbox Code Playgroud)
所以,如果你想使用jasmine返回一个值来监视它,你需要使用原始调用的第一个参数调用success函数,如下所示:
spyOn(navigator.geolocation,"getCurrentPosition").andCallFake(function() {
var position = { coords: { latitude: 32, longitude: -96 } };
arguments[0](position);
});
Run Code Online (Sandbox Code Playgroud)
如果你想让它看起来像是一个错误被返回,你想要使用原始调用的第二个参数调用错误函数,如下所示:
spyOn(navigator.geolocation,"getCurrentPosition").andCallFake(function() {
arguments[1](error);
});
Run Code Online (Sandbox Code Playgroud)
编辑以显示完整示例:
这是您使用Jasmine测试的功能:
function GetZipcodeFromGeolocation(onSuccess, onError) {
navigator.geolocation.getCurrentPosition(function(position) {
// do something with the position info like call
// an web service with an ajax call to get data
var zipcode = CallWebServiceWithPosition(position);
onSuccess(zipcode);
}, function(error) {
onError(error);
});
}
Run Code Online (Sandbox Code Playgroud)
这将在您的spec文件中:
describe("Get Zipcode From Geolocation", function() {
it("should execute the onSuccess function with valid data", function() {
var jasmineSuccess = jasmine.createSpy();
var jasmineError = jasmine.createSpy();
spyOn(navigator.geolocation,"getCurrentPosition").andCallFake(function() {
var position = { coords: { latitude: 32.8569, longitude: -96.9628 } };
arguments[0](position);
});
GetZipcodeFromGeolocation(jasmineSuccess, jasmineError);
waitsFor(jasmineSuccess.callCount > 0);
runs(function() {
expect(jasmineSuccess).wasCalledWith('75038');
});
});
});
Run Code Online (Sandbox Code Playgroud)
此时,当您运行规范时,它会告诉您,如果您的Web服务正常工作,您的Web服务会为您提供正确的邮政编码,以提供您提供的纬度和经度.