Angular ui bootstrap $uibModalInstance 分解单元测试

2024-01-19

通过使用$uibModal服务打开模态窗口,我们需要注入$uibModalInstance在模态控制器中关闭或关闭模态窗口,此注入会破坏我的单元测试。

脚本.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();
  };
}

模态.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>

索引.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 http://plnkr.co/edit/w4D2c25aa45OSXn3ZsJb?p=preview

注意:我面临的问题不是关闭模态(因为它有效),问题是我的单元测试之前工作$uibModalInstance被注入。

抛出的错误是:

Error: [$injector:unpr] Unknown provider: $uibModalInstanceProvider <- $uibModalInstance

欢迎任何建议,感谢您的阅读。


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Angular ui bootstrap $uibModalInstance 分解单元测试 的相关文章

随机推荐