簡體   English   中英

使用Jasmine / Angular測試異步功能

[英]Test async function with Jasmine/Angular

有以下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',因為函數是異步的。 如何正確測試此代碼? 提前致謝。

  • 在這種情況下,請在測試中使用茉莉花模擬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); }); }) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM