当您调用地理位置代码时,它看起来像这样:
navigator.geolocation.getCurrentPosition(onSuccess, onError);
这意味着您正在调用它并传递它的功能:
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
}
因此,如果您想使用 jasmine 返回值来监视它,您需要使用原始调用的第一个参数调用成功函数,如下所示:
spyOn(navigator.geolocation,"getCurrentPosition").andCallFake(function() {
var position = { coords: { latitude: 32, longitude: -96 } };
arguments[0](position);
});
如果你想让它看起来像返回了一个错误,你会想使用原始调用的第二个参数来调用错误函数,如下所示:
spyOn(navigator.geolocation,"getCurrentPosition").andCallFake(function() {
arguments[1](error);
});
编辑以显示完整示例:
这是您使用 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);
});
}
这将在您的规范文件中:
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');
});
});
});
此时,当您运行规范时,它会告诉您,如果您的 Web 服务正常工作,您的 Web 服务会根据您提供的纬度和经度为您提供正确的邮政编码。