1

我正在使用ng-describe(我必须说,很棒)为 angularJS 编写业力单元测试。

我有两个指令。我想测试testing需要somethingController.

code:

angular.module('A', [])
.directive('testing', function($compile){
  return {
    restrict: 'E',
    template: '<div>THIS TEST</div>',
    replace:true,
    controllerAs: 'testA',
    bindToController: true,
    require: '^something',
    link: function(){
      console.log('this is controller');
    }
  };
})
.directive('something', function(){
  return {
    restrict: 'E',
    template: '<div id="div1">THIS IS PARENT</div>',
    replace:true,
    controllerAs: 'sth',
    bindToController: true,
    controller: function($scope,$compile){
      console.log('this is something');
      angular.element(document.getElementById('div1'))
      .prepend($compile('<div>THIS IS compile</div>')($scope));
    }
  };
});

如果我使用手动编译,我能够成功运行这些测试。

ngDescribe({
  name:'a',
  modules: 'A',
  inject:['$compile'],
  exposeApi:true,
  only:true,
  tests: function(deps, describeApi){
    it('asdfasdf', function(){
      var mockModalCtrl = {};
      deps.element = angular.element('<testing></testing>');
      deps.element.data('$somethingController', mockModalCtrl);
      inject(function($compile, $rootScope){
        $compile(deps.element)($rootScope.$new());
      });
      deps.step();
    });
  }
});

如果我不进行手动编译,最终会出现以下错误:

Error: [$compile:ctreq] Controller 'something', required by directive 'testing', can't be found

我真正想做的是:

我正在尝试最大限度地使用 ng-describe 并摆脱手动编译。我试过使用describeApi.setupControllershttps://github.com/kensho/ng-describe#secondary-options我没有运气。

  • 使用 adescribeApi.setupElement('<testing></testing>')会给我留下上面显示的 $compile 错误。
  • 使用describeApi.setupControllers('something')给我留下了错误:Error: [ng:areq] Argument 'something' is not a function, got undefined
  • 我试图设置名为something, somethingController,的控制器$something$somethingController但我也在undefined, not a function那里看到了错误。

有没有办法让这个工作?目前我无法在网上找到解决方案...

4

1 回答 1

3

好的。显然,在 SO 上输入一个问题会让你的大脑思考比平时多一倍。我想出了解决方案:

var mockModalCtrl = {};
deps.element = angular.element('<testing></testing>');
deps.element.data('$somethingController', mockModalCtrl);
describeApi.setupElement(deps.element);
于 2015-11-05T15:07:29.610 回答