有以下Angular代码:
$scope.clickByPoint = function(marker, eventName, point) {
var geocoder, location;
$scope.options.info.point = point;
$scope.options.info.show = true;
$scope.searched = false;
$scope.address = "";
geocoder = new google.maps.Geocoder();
location = {
lat: parseFloat(point.latitude),
lng: parseFloat(point.longitude)
};
geocoder.geocode({location: location}, function(results, status) {
$scope.searched = true;
if (status === google.maps.GeocoderStatus.OK) {
$scope.address = results[0].formatted_address;
}
$scope.$digest();
});
};
我的茉莉花测试:
describe('$scope.clickByPoint', function() {
var point;
beforeEach(inject(function(_Point_) {
point = _Point_.build('PointName', { latitude: 0, longitude: 0 });
}));
describe('try to find the address', function() {
it('initialize google maps info window', function() {
$scope.clickByPoint(null, null, point)
expect($scope.searched).toEqual(true);
});
})
});
正如您所看到的,我正在尝试测试'scope.searched'变量已更改,但它始终为'false',因为函数是异步的。如何正确测试此代码?提前谢谢。
答案 0 :(得分:0)
在这种情况下,使用jasmine在测试中使用google.maps.Geocoder()的模拟,因为,您正在测试clickByPoint()逻辑而不是Google maps api。
var geocoder = new google.maps.Geocoder();
jasmine.createSpy("geocode() geocoder").andCallFake(function(location, callback) {
// no wait time ...
var results = {fake:'', data:''};
var status = google.maps.GeocoderStatus.OK; // get OK value and set it OR redefine it with a Spy.
callback(result, status);
});
现在您可以使用您的测试:
describe('try to find the address', function() {
it('initialize google maps info window', function() {
$scope.clickByPoint(null, null, point);
expect($scope.searched).toEqual(true);
});
})