2015-09-16 54 views
1

有以下角度代碼:測試異步功能/角

$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 '變量被改變了,但它總是'假',因爲函數是異步的。我如何正確測試這段代碼?提前致謝。

回答

0
  • 在這種情況下,測試使用google.maps.Geocoder()的模擬,用茉莉花,因爲你正在測試clickByPoint()邏輯,而不是谷歌地圖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); 
         }); 
        })