测试角度组件templateUrl

时间:2016-10-25 14:47:00

标签: angularjs unit-testing sinon

我在测试此模板html时遇到问题。我正在使用业力和罪恶。我收到未知提供商:_Provider< - _< - service 错误。

这是我的组件:

angular.
  .module('app.component.thing-foo')
  .component('thingFoo', {
    templateUrl: 'components/thing-foo/thing-foo.html',
    controller: ThingFooController,
    bindings: {
      thing: '<',
      onSelect: '&'
    }
  });

function ThingFooController($log, service) {
  var ctrl = this;
  ctrl.$onInit = $onInit;
  ctrl.$onChanges = $onChanges;
  ctrl.thingList = [];

  function $onInit(){
    getThingList();
  }

  function $onChanges(changesObj){
    if (changesObj.thing) {
      ctrl.thing = angular.copy(changesObj.thing.currentValue);        
  }

  function getThingList(){
    service.getThings()
     .then(function (result) {
       ctrl.thingList = result.things;
     }, function (error) {
       $log.error('Did not work: $0', error);
     })
  }

  function selectionChanged(selected) {
    ctrl.onSelect({thing: selected});
  }
}

事-foo.html:

<span ui-dropdown class="dropdown-toggle">
  <a href id="query-menu-label" ui-dropdown-toggle>
    Thing Picker <b class="caret"></b>
  </a>
  <ul calss="dropdown-menu" aria-labelledby="query-menu-label" role="menu">
    <li role="presentation" ng-repeat="thing in $ctrl.thingList">
      <a role="menuitem" ng-click="$ctrl.selectionChanged(thing)">{{ thing }}</a>
    </li>
   </ul>
</span>

我包含了失败的spec文件部分:

beforeEach(inject(function(_$compile_, _$componentController_, _$rootScope_){
  $compile = _$compile_;
  $componentController = _$componentController_;
  $rootScope = _$rootScope_;
}));

beforeEach(function(){
  scope = $rootScope.$new();
  element = angular.element('<thing-foo></thing-foo>');
  service = {
   getThings: sinon.stub();
  };
  locals = {
   service: service
  };
});

it('loads html', function(){
 var tag = $compile(element)(scope);
 scope.$apply();
 expect(tag.html()).to.exist();
});

这里有很多代码,但我想确保包含所有内容。我认为问题是ng-repeat中的$ ctrl.getThingList。我应该注意服务一些怎么样?如果是这样,我该怎么做?我没有很多练习角度单位测试。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

不完全确定,但可能尝试配置$ provider来注入您的服务? 像这样:

// Put this before your first beforeEach
beforeEach(module(function($provide) {
   $provide.value('service', service);
}