Angular 单元测试:隔离模块上定义的某些组件

Angular Unit Testing: Isolate certain components defined on module

我继承了一个使用 Karma 和 Jasmine 的大型 AngularJS 项目,我正在尝试遵循在我之前制定的约定,但在单元测试 directive/controller 模块时遇到了麻烦。每个模块定义如下:

angular
  .module('ap.panels.ContinuousDeliverySearchPanel', [])
  .directive('continuousDeliverySearchPanel', ContinuousDeliverySearchPanel)
  .controller('continuousDeliverySearchPanelCtrl', ContinuousDeliverySearchPanelCtrl);

function ContinuousDeliverySearchPanel() {
  return {
    restrict: 'E',
    templateUrl: '/panels/continuous-delivery-search-panel/continuous-delivery-search-panel.html',
    controller: 'continuousDeliverySearchPanelCtrl',
    controllerAs: 'vm',
    bindToController: true,
    scope: {
      search: '='
    }
  };
}

模块上同时定义了指令和控制器,并且控制器绑定到指令。我想创建两组测试,一组用于控制器,一组用于指令。我 运行 遇到的问题是在测试指令时,我只是想测试元素是否已正确编译,但不得不处理控制器的 http 调用和依赖项。这是我的指令测试的示例:

describe('ap.panels.ContinuousDeliverySearchPanel', function () {

  var scope, template, element;

  beforeEach(module('ap.panels.ContinuousDeliverySearchPanel'));

  beforeEach(inject( function ($rootScope, $compile){
    scope = $rootScope.$new();
    template = angular.element('<continuous-delivery-search-panel></continuous-delivery-search-panel>');
    element = $compile(template, scope);
    scope.$digest();
  }));

  it('Should: compile search panel directive', function() {
    expect(element).toBeDefined();
  });

});

当 $compile 被调用时,continuousDeliverySearchPanelCtrl 运行s 并开始抛出错误,因为它有一堆依赖项和 http 请求没有被模拟或处理。但是,我不想模拟这些,因为我什至没有测试控制器。我想在另一个文件中单独执行此操作,我在其中隔离控制器进行测试。

有没有办法传入空控制器或仅隔离指令以成功测试它是否编译?

是的,您只需要模拟控制器即可。

尝试这样的事情:

module('foobar', function($provide, $controllerProvider) {
        $controllerProvider.register('FooBarController', function($scope) {
            // Controller Mock                
        });

    });

documentation for controllerProvider

documentation for $provide