Is it possible to mock a local variable in an angular factory out of karma?

I have below code:

'use strict';

angular
    .module('testmodule')
    .factory('TestService', ['$q', '$timeout',
        function ($q, $timeout) {

      

var timeoutRetries = 0; // need to mock it here

            var api = new TestApi();

            function getResults(id, prevDeferred) {
                var deferred = prevDeferred || $q.defer();

                function handleSuccessResponse(data) {
                    if (data.status === 'ready') {
                        results.put(id, data);
                        deferred.resolve(data);
                    } else {                        

      

if (++ timeoutRetries> 30) {// He won't be here

                            handleErrorResponse();
                        } else {
                            $timeout(function () {
                                getResults(id, deferred);
                            }, 2000);
                        }
                    }
                }

                function handleErrorResponse(response) {
                    deferred.reject(response);
                }

                if (results.get(id)) {
                    deferred.resolve(doSomething.get(id));
                    return deferred.promise;
                }

                api.get({id: id}).then(handleSuccessResponse, handleErrorResponse);
                return deferred.promise;
            }

            return {
                getResults: getResults
            };
        }]);

      

I'm trying to poke fun at the timeoutRetries entry from karma, but I can't seem to do it. Is this the perfect way to declare it or do I need to move the variable into some function and update, or is this the best way to mock karma?

Tried with injection, declared a variable before calling the function. Still no success.

+1


source to share


1 answer


You need to close this branch for it to automatically cover the local variable. It looks like your test doesn't cover this scenario.

You depend on state data for results. If it's ready, you return the results. If there is no increment timeout and if it is> 30 then re-issue the else error message for the results again until you get the status as done or the timeout is 30.

You can easily cover another branch.

var isReadyTrue = false;
$httpBackend.expectGET(url).respond(function () {
            return [201, function(){
if (isReadyTrue) {
results.data = 'Ready';
} else {
results.data = 'Not Ready';
}
isReadyTrue = true; // Next result will be ready..

return results;
}];
        });

      



We cannot mock a local variable, but we can come up with a script to cover it.

The first result will not be ready, so the timeout will be 1 and go for polling. The next result is returned with the data Ready.

You can poke fun at 30 timeout using the combination above and $ timeout

+1


source







All Articles