Angular ui bootstrap $ uibModalInstance分解单元测试

时间:2015-12-27 17:13:16

标签: angularjs twitter-bootstrap angular-ui-bootstrap bootstrap-modal

通过使用$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

欢迎任何建议,谢谢阅读。

0 个答案:

没有答案