用Jasmine/Angular测试async函数

Test async function with Jasmine/Angular

本文关键字:async 函数 测试 Angular Jasmine      更新时间:2023-09-26

有以下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。搜索'变量被改变,但它总是'假',因为函数是异步的。我怎样才能正确地测试这段代码?

  • 在这种情况下,在测试中使用Google .maps. geocoder()的模拟,使用jasmine,因为您正在测试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);
            });  
        })