Inability to get data in karma function from controller transfer statement

            /*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 do not receive items in the karma test. the controller calls the service to receive data in async. this process is handled by an angular promise. but the problem is with recording the test case>, because the controller function returns before receiving data from the> service. how can i solve this problem?

+4
source share
1 answer

Replace

scope.getCheckoutItems();
console.log(scope.cart);

by

scope.getCheckoutItems();
scope.$apply();
console.log(scope.cart);

Promise callbacks are called when the $ scope is applied.

+3
source

Source: https://habr.com/ru/post/1589364/


All Articles