2

我應該如何去測試使用業力和茉莉花的確認框的結果?我有一些基本的測試正在運行,這要感謝這裏有幫助的人,但是我很難嘲笑ionicPopup。單元測試確認Popup Ionic Framework Karma

這將是理想的,如果我可以通過ng-click來測試從盒子到所有可能的結果。

查看:

<button ng-click="openPopup()">Open Popup</button> 

控制器:

angular.module('starter.thisController', []) 

.controller('ThisCtrl', function($scope, $state, $timeout, $ionicPopup) { 
    $scope.openPopup = function() { 
     var openPopup = $ionicPopup.confirm({ 
      title: 'Confirm', 
      template: 'Are you sure?' 
     }); 

     openPopup.then(function(res) { 
      if(res) { 
      $scope.confirmClicked(); 
      } 
     }); 

     $timeout(function() { 
      openPopup.close(); 
      }, 5000); 
    }; 

    $scope.confirmClicked = function() { 
     alert("User Clicked Confirm!!!"); 
    }; 
}); 

電流試驗:

describe('This Controller', function() { 
    var scope, state, timeout, ionicPopup; 
    ionicPopup = jasmine.createSpyObj('$ionicPopup spy', ['confirm']); 

    beforeEach(module('starter.thisController')); 

    beforeEach(inject(function($rootScope, $controller) { 
     scope = $rootScope.$new(); 
     $controller('ThisCtrl', { 
      '$scope': scope, 
      '$state': state, 
      '$timeout': timeout, 
      '$ionicPopup': ionicPopup 
     }); 
    })); 

    describe('Popup', function() { 
     it('should be defined', function() { 
      expect(ionicPopup).toBeDefined(); 
     }); 
    }); 
}); 

感謝您的幫助,您可以提供:d。

回答

3

我有同樣的問題,我通過使用spyOn解決了它。我會盡力迎合你的榜樣。

describe('This Controller', function() { 
    var scope, state, timeout, $ionicPopup, $q 

    beforeEach(module('starter.thisController')); 

    beforeEach(inject(function($rootScope, $controller, _$ionicPopup_, _$q_) { 
     scope = $rootScope.$new(); 
     $ionicPopup = _$ionicPopup_; 
     $q = _$q_; 
     $controller('ThisCtrl', { 
      '$scope': scope, 
      '$state': state, 
      '$timeout': timeout, 
      '$ionicPopup': $ionicPopup 
     }); 
    })); 

    describe('$scope.openPopup', function() { 

     it('should call confirmClicked function if ok is clicked in the confirm popup', function() { 
      var deferred = $q.defer(); 
      deferred.resolve(true); //ok is clicked 
      spyOn($ionicPopup, 'confirm').and.callFake(function(){return deferred.promise}); 
      scope.openPopup(); 
      scope.$digest(); 
      expect(scope.confirmClicked).toHaveBeenCalled(); 
     }); 

     it('should not call confirmClicked if cancel is clicked in the confirm popup', function() { 
      var deferred = $q.defer(); 
      deferred.resolve(false); //cancel is clicked 
      spyOn($ionicPopup, 'confirm').and.callFake(function(){return deferred.promise}); 
      scope.openPopup(); 
      scope.$digest(); 
      expect(scope.confirmClicked).not.toHaveBeenCalled(); 
     }); 
    }); 
}); 

這裏的主要區別是,我們注入真正的$ ionicPopup,然後覆蓋與spyOn行爲。

+0

Thanks @ FrancisA..Saved my huge time ... !! –