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