繁体   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