【发布时间】:2016-08-04 07:17:05
【问题描述】:
我创建了通过 httppost 请求返回产品详细信息的服务
我有控制器,我通过它调用服务__getProductService.getproductDetailsPull().then(function(response){__
我在控制器中获取数据
我通过注入 spy 在 jasmine-karma 中为此编写了一个测试用例
__spyOn(getProduct, 'getproductDetailsPull').and.returnValue(deferred.promise);__
**但是我的承诺出错了**
错误 1
Expected a spy, but got deleteCtrl({ }).
错误 2
.then is not a function
服务代码
var myapp = angular.module('abcservice');
myapp.service('getProductService',function($http,$q){
var productDetails = [];
var productResponse = null;
this.setproduct= function() {
var obj = {
adminId : 15,
productOrderID: 174824929577
};
if (this.productResponse == null) {
this.productResponse = $http.post('someurl',obj).success(function(data, status, headers,config) {
this.productResponse = mapJson(data);
}).error(function(data, status, headers,config)
{
console.log("error while fetching data from spring controller:" +error);
});
}
return this.productResponse;
};
this.getproductDetailsPull = function(productResponse) {
return this.productResponse;
};
}
控制器代码
angular
.module('getCtrl', []);
getCtrl.$inject = ['$scope', '$http', '$rootScope', 'getProductService'];
function getCtrl($scope, $http, $rootScope, getProductService) {
getProductService.getproductDetailsPull().then(function(response){
$scope.displayData = response.data.productorder;
$scope.lineItemData = response.data.OrderItem;
}
}
Jasmine 测试用例
describe('getCtrl Test', function() {
var $scope = null;
var $getProduct = null;
var $rootScope = null;
var deferred,$q;
beforeEach(module('abcservice','getCtrl'));
beforeEach(inject(function (_$controller_,$rootScope,getProduct,_$q_) {
$controller = _$controller_;
$scope = $rootScope.$new();
$q = _$q_;;
deferred = _$q_.defer();
spyOn(getProduct, 'getproductDetailsPull').and.returnValue(deferred.promise);
controller = $controller('getCtrl', { $scope: $scope,$rootScope: $rootScope,getProduct:getProduct });
}));
it('Exists controller, function() {
expect(controller).toHaveBeenCalled();
});
});
【问题讨论】:
标签: angularjs unit-testing testing jasmine