【发布时间】:2016-10-25 14:47:00
【问题描述】:
我在测试此模板 html 时遇到问题。我正在使用 karma 和 sinon。我收到此 Unknown provider: _Provider 错误。
这是我的组件:
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});
}
}
thing-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>
我将包含失败的规范文件部分:
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。我应该以某种方式注入服务吗?如果是这样,我该怎么做?我没有很多为 Angular 编写单元测试的练习。任何帮助表示赞赏。
【问题讨论】:
标签: angularjs unit-testing sinon