首页 > 代码库 > 如何测试注入modalInstance的controller

如何测试注入modalInstance的controller

 

 

使用AngularUI-Bootstrap的模态框(modal)时,需要在controller注入$modalInstance.

//$modalInstance代表一个独立的模态框实例//它和$modal的用法是不一样的angular.module(‘ui.bootstrao.demo‘).controller(‘ModalInstanceCtrl‘,function($scope,$modalInstance){  $scope.item = ‘hello‘;  $scope.ok = function () {    $modalInstance.close($scope.item);  };  $scope.cancel = function () {    $modalInstance.dismiss(‘cancel‘);  };});

 

但是,使用jasmine测试时,在测试代码中注入$modalInstance时可能会出现错误:unknown provider: $modalInstanceProvider<-$modalInstance.原因可能是$modalInstance只能在控制器中注入(我也不知道具体原因- -)

 

由于modal和modalInstance是第三方注入的服务,因此,我们只需要测试modal和modalInstance是否在我们的控制器代码上被调用.我们可以通过创建一个模拟的modalInstance对象来实现.

describe(‘控制器测试:ModalInstanceCtrl‘,function(){  beforeEach(module(‘app‘));  beforeEach(inject(function($controller,$rootScope){    var ModalInstanceCtrl,scope;    scope = $rootScope.$new();    //创建一个模拟的modalInstance对象    modalInstance = {      close: jasmine.createSpy(‘modalInstance.close‘);      dismiss: jasmine.createSpy(‘modalInstance.dismiss‘);      result: {        then: jasmine.createSpy(‘modalInstance.then‘);     }    };    ModalInstanceCtrl = $controller(‘ModalInstanceCtrl‘,{      $scope: scope;      $modalInstance: modalInstance    });        it(‘当调用ok时,应该close模态框‘,function(){      scope.ok();
expect(modalInstance.close).toHaveBeenCalledWith(true); });
it(‘当调用cancel,应该dismiss模态框‘,function(){
scope.cancel;
expect(modalInstance.dismiss).toHaveBeenCalledWith(true);
}) })); });

 

如何测试注入modalInstance的controller