我创建了一个角度自定义指令,其中包含一个名为scriptingService的服务。目标是使用spyOn模拟服务调出。这是测试的一部分:
beforeEach(inject(function ($rootScope, $compile,_scriptingService_) {
scope = $rootScope.$new();
scope.row = 1;
scriptingService = _scriptingService_;
Restangular = _Restangular_;
spyOn(Restangular, 'all').and.callThrough();
spyOn(scriptingService, 'getScript').and.callThrough();
element = angular.element('<ul id="rows" ui-list="row">');
$compile(element)(scope);
scope.$digest();
}));
这是指令代码:
.directive('uiList', [
function(scriptingService) {
return {
scope: {
lengthModel: '=uiList'
},
link: function(scope, elm, attrs) {
scope.$watch('lengthModel', function(newVal) {
scope.test=2;
console.log('kut');
scriptingService.getScript(request).then(function(scripts){
scope.scripts = scripts;
});
});
}
};
}
]);
但是我收到了错误:
RestangularProvider <- Restangular <- scriptingService
如何模拟scriptingService并确保调用该方法? Plunker ref:http://plnkr.co/edit/CDc7EV?p=preview
答案 0 :(得分:0)
这里有几个问题:
与上述评论一样,您需要为callThrough
功能使用较新版本的jasmine,而Restangular
需要使用下划线,因此需要在html中引用文件
此外,需要为您的指令修复依赖注入,因为它无法正确注入scriptingService
,因为scriptingService.getScript
从未允许它调用scriptingService
是undefined
。问题在于
[ function(scriptingService) {}]
无法将scriptingService
注入uiList
。它最终只是undefined
。
它必须是
['scriptingService', function(scriptingService) {}]
OR
function(scriptingService) {}
供参考:https://docs.angularjs.org/guide/di#dependency-annotation
request
在此代码中被使用时从未被定义,我不确定它应该是什么。
scriptingService.getScript(request).then(function(scripts) {
scope.scripts = scripts;
});
修复这些问题后,测试仍然失败,说错误:意外请求:GET /脚本。
我能够通过将$httpBackend
(这是一种用于模拟角度的http调用的服务)注入测试并期望请求来解决这个问题。所以我改变了
inject(function ($rootScope, $compile,_scriptingService_,_Restangular_)
要
inject(function ($rootScope, $compile,_scriptingService_,_Restangular_, $httpBackend)
并添加了此
$httpBackend.expectGET("/scripting").respond([]);
在spyOn
之后,测试通过了。我不确定这个http调用应该返回什么,但这只是一个如何测试它的例子。
供参考: https://docs.angularjs.org/api/ngMock/service/ $ httpBackend