/*This is my cart service function:*/ getCheckoutItems: function() { var defer = $q.defer(); var response = { result: true,data: '',err: '' }; if (!angular.isUndefined(productListSample)) { response.data = productListSample; defer.resolve(response); } else { response.result = false; response.err = 'error'; defer.reject(response); } return defer.promise; } /*This is my controller function:*/ $scope.cart = { items: [],phoneNo: '' }; $scope.getCheckoutItems = function() { CartService.getCheckoutItems().then(function(result) { $scope.cart.items = result.data; },function(err) { /* * Todo: handle when service fails to retrieve data. */ }); }; /* This is karma test function */ it('get checkout items',inject(function($controller) { $controller('Ctrl',{ $scope: scope }); scope.getCheckoutItems(); console.log(scope.cart); }));
I am not getting cart items in karma test.
controller calls service for getting data in async. this process is
handled by angular promise.but problem with writing test case > because controller function returns before getting data from > service.
how can I solve this problem?
解决方法
更换
scope.getCheckoutItems(); console.log(scope.cart);
通过
scope.getCheckoutItems(); scope.$apply(); console.log(scope.cart);
当范围为$apply时,将调用Promise回调.