使用AngularUI-Bootstrap的模態框(modal)時,須要在controller注入$modalInstance.app
//$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只能在控制器中注入(我也不知道具體緣由- -)ide
因爲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); }) })); });