通过使用$uibModal
服务打开一个模态窗口,我们需要在模态控制器中注入$uibModalInstance
来关闭或关闭模态窗口,这个注入会破坏我的单元测试。
的script.js
angular.module('demo', ['ui.bootstrap'])
.controller('MainController', MainCtrl)
.controller('UIModalController', UIModalCtrl);
/** @ngInject */
function MainCtrl($log, $uibModal) {
var vm = this;
vm.openModal = function() {
$log.log('Opening Modal..');
$uibModal.open({
templateUrl: 'modal.html',
controller: 'UIModalController',
controllerAs: 'modal'
});
};
}
/** @ngInject */
function UIModalCtrl($log, $uibModalInstance) {
var vm = this;
vm.ok = function() {
$log.log('Ok clicked');
$uibModalInstance.close();
};
}
modal.html
<div class='modal-header'>
<h3>Hi there!</h3>
</div>
<div class='modal-body'>
Some content goes here
</div>
<div class='modal-footer'>
<button class='btn btn-primary' ng-click='modal.ok()'>Ok</button>
</div>
index.spec.js
describe('MainContrller', function() {
var vm;
beforeEach(module('demo'));
beforeEach(inject(function(_$controller_) {
vm = _$controller_('UIModalController', {});
}));
it('should define a ok function', function() {
expect(vm.ok).toBeDefined();
expect(angular.isFunction(vm.ok)).toBeTruthy();
});
it('should close the modal window if Ok button is pressed', inject(function($uibModalInstance) {
spyOn($uibModalInstance, 'close').and.callThrough();
vm.ok();
expect($uibModalInstance.close).toHaveBeenCalled();
}));
});
这是一个用来说明问题的傻瓜:http://plnkr.co/edit/w4D2c25aa45OSXn3ZsJb?p=preview
注意:我面临的问题不是关闭模态(导致它起作用),问题是我的单元测试在注入$uibModalInstance
之前工作。
抛出的错误是:
Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance
欢迎任何建议,谢谢阅读。