我正在尝试为函数编写jasmine测试用例,该函数又调用另一个函数并返回响应。好像调用了函数,但我没有得到函数内设置的值。
控制器功能:
angular.module('serviceApp')
.controller('startWorkscopeCtrl', function ($rootScope, $log, $scope, CommentService) {
$scope.getTextById = function (id) {
CommentService.get({ id: id }, function (response) {
$scope.text = response;
$scope.textCount = $scope.text.length;
});
};
});
该服务在另一个js文件中被引用,在该文件中,它对后端服务进行了休息服务调用。
angular.module('restServiceModule', ['ngResource'])
.factory('CommentService', function($resource){
return $resource(
{
get: {
method: 'GET',
isArray: true,
url: window.urlPrefix + '/commentservice/:id',
params: {
id: '@id'
}
}
});
})
测试用例:
var mockTextComment;
var fakeText = ['testPass'];
beforeEach(function(){
mockTextComment = {
get: function(){
return fakeText;
}
};
});
it('should get comments by asset id', function () {
spyOn(mockTextComment, 'get');
inject(function ($controller) {
ctrl = $controller('startWorkscopeCtrl', {
$scope: scope,
CommentService: mockTextComment
});
scope.getTextById(40107);
expect(scope.textCount).toEqual(1);
});
});
有了这个,我得到以下错误:
**Expected undefined to equal 1.
Error: Expected undefined to equal 1.**
不确定我在哪里做错了。任何关于此的指示都会有所帮助。
答案 0 :(得分:0)
看起来CommentService.get
没有返回值;它在完成时回调函数。因此,CommentService
模拟看起来像这样:
var mock = {
get : function(arg1, callback){
callback(fakeText);
}
}