我创建的服务通过httppost请求返回产品详细信息
我有控制器,我称之为服务__getProductService.getproductDetailsPull().then(function(response){__
我在控制器中获取数据
我通过注入间谍
在茉莉花业中为此写了一个测试用例__spyOn(getProduct, 'getproductDetailsPull').and.returnValue(deferred.promise);__
**但我的承诺错误**
Expected a spy, but got deleteCtrl({ }).
.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;
}
}
茉莉花测试用例
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();
});
});
答案 0 :(得分:1)
您有输入错误,getProduct不是您服务的名称。您需要注入以下服务:
beforeEach(inject(function (_$controller_,$rootScope,getProductService
间谍应该是int格式的spyOn(对象," methodName"),所以在你的情况下:
spyOn(getProductService, 'getproductDetailsPull')
考虑这样做是为了你的承诺:
spyOn(getProductService, 'getproductDetailsPull').and.returnValue($q.when())
你的测试用例有点奇怪我假设你只是这样做才能让事情有效但你可能想要这样的东西:
it('Product is fetched, function() {
scope.$digest(); // if your using $q you need this (maybe move it to before call)
expect(getProductService.getproductDetailsPull).toHaveBeenCalled();
});