angularjs – 无法从控制器延迟语句中获取karma函数中的数据

前端之家收集整理的这篇文章主要介绍了angularjs – 无法从控制器延迟语句中获取karma函数中的数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/*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回调.

猜你在找的Angularjs相关文章