0

我終於學習如何使用我寫的較老的angularjs應用程序進行測試。我在我的控制器中有幾個模式,我無法弄清楚我的生活如何確保'modalInstance.result.then'中的代碼運行並測試它。測試modalInstance.result然後

我搜索了Google和SO,並找到了測試他們模態的人的例子,但到目前爲止他們似乎都涉及測試模態控制器本身。

如何獲得該承諾(modalInstance.result.then)來解決?我試過運行$ modal.close(),但沒有出現錯誤。我嘗試過使用茉莉花間諜等多種方式來嘲笑modalInstance和$ modal。當談到測試時,我的無知使我躊躇了。任何幫助都會被處理。

這裏是我的controller.js:

(function() { 
    var comment = angular.module('APP.comment', ['APP.user']); 

    var commentController = function($scope, $modal) { 

     var self = this; 

     self.addComment = function(newComment) { 

     var modalInstance = $modal.open({ 
      templateUrl: 'views/commentModal.html', 
      backdrop: 'static', 
      windowClass: 'modal', 
      controller: 'commentModalController', 
      controllerAs: 'commentCtrl', 
      resolve: { 
       newComment: function() { 
        return newComment; 
       } 
      } 
     }); 

     modalInstance.result.then(function(data) { 
      // How do I test that the function or branches here 
      // were run? 
      if (data.length === 2) { 
       // do this thing 
      } else { 
       // do this other thing 
      } 
     }); 
     }; 
    }; 

    commentController.$inject = ['$scope', '$modal']; 
    comment.controller('commentController', commentController); 
}()); 

這裏是測試我到目前爲止:

describe('Unit: commentController', function() { 

    var $rootScope, 
     $scope, 
     $controller, 
     $modal; 

    beforeEach(module('APP.comment')); 

    beforeEach(inject(function(_$rootScope_, _$controller_, _$modal_) { 

     $modal = _$modal_; 

     $rootScope = _$rootScope_; 
     $scope = $rootScope.$new(); 

     $controller = _$controller_('commentController as commentCtrl', { 
      $scope: $scope, 
      $modal: $modal, 
     }); 

    })); 

    it('should have controller defined', function() { 
     expect($scope.qaCtrl).toBeDefined(); 
    }); 

    it('should have method defined', function() { 
     expect($scope.qaCtrl.addComment).toBeDefined(); 
    }); 

    describe('$scope.commentCtrl.addComment', function() { 
     it('should open modal', function() { 
      $scope.commentCtrl.addComment(); 
     }); 
    }); 
}); 

我這裏有一個plnkr:
http://plnkr.co/edit/YtYVPReH9yysZXPjbsC0?p=preview

回答

3
it('should open modal', inject(function($q) { 
    var fakeResult = { 
    result: $q.when([]) 
    }; 
    spyOn($modal, 'open').and.returnValue(fakeResult); 

    $scope.commentCtrl.addComment(); 

    $scope.$apply(); 

    // now check that the right thing has been done, given the empty array returned 
})); 
+0

那做的伎倆,謝謝你的答案! – Woody2143

相關問題