UI-Bootstrapのmodalのテストで、$modalInstanceを使うControllerをテストしようとして、$modalInstanceをinjectしようとするところでUnknown providerとエラーが出る
公式のサンプルでいうと、ModalInstanceCtrl部分のテスト。
// modal-demo.js var ModalDemoCtrl = function ($scope, $modal, $log) { $scope.items = ['item1', 'item2', 'item3']; $scope.open = function (size) { var modalInstance = $modal.open({ templateUrl: 'myModalContent.html', controller: ModalInstanceCtrl, size: size, resolve: { items: function () { return $scope.items; } } }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; }; // Please note that $modalInstance represents a modal window (instance) dependency. // It is not the same as the $modal service used above. var ModalInstanceCtrl = function ($scope, $modalInstance, items) { $scope.items = items; $scope.selected = { item: $scope.items[0] }; $scope.ok = function () { $modalInstance.close($scope.selected.item); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; };
beforeEachで$modalInstanceをinjectしようとしているところで
#modal_instance_spec.coffee "use strict" describe "Controller: ModalInstanceCtrl", -> # load the controller"s module beforeEach module "myApp" ModalInstanceCtrl = {} scope = {} modalInstance = {} httpBackend = {} # Initialize the controller and a mock scope beforeEach inject ($controller, $rootScope, _$httpBackend_,_$modalInstance_) -> scope = $rootScope.$new()
こんなエラー
Error: [$injector:unpr] Unknown provider: $modalInstanceProvider <- $modalInstance
こんなときはmodalInstanceをmockにしてしまえばOK.
#modal_instance_spec.coffee "use strict" describe "Controller: ModalInstanceCtrl", -> # load the controller"s module beforeEach module "myApp" ModalInstanceCtrl = {} scope = {} modalInstance = {} httpBackend = {} # Initialize the controller and a mock scope beforeEach inject ($controller, $rootScope, _$httpBackend_) -> scope = $rootScope.$new() httpBackend = _$httpBackend_ modalInstance = close: jasmine.createSpy("modalInstance.close") dismiss: jasmine.createSpy("modalInstance.dismiss") result: then: jasmine.createSpy('modalInstance.result.then') ModalInstanceCtrl = $controller "ModalInstanceCtrl", { $scope: scope $modalInstance: modalInstance } it "cancelを呼ぶと、modalをdismissすること", -> scope.cancel() expect(modalInstance.dismiss).toHaveBeenCalled() #........