mercredi 14 septembre 2016

How to send mocked response data to called through $http call?

I have a controller that calls a service and sets some variables. I want to test that those variables get set to the response.

My Controller:

tankService.getCurrentStats().success(function (response) {
            $scope.stats.tankAvgHours = response.tankAvgHours;
            $scope.stats.stillAvgHours = response.stillAvgHours;
            $scope.stats.stillRemaining = response.stillRemaining;
            $scope.stats.tankRemaining = response.tankRemaining;
            $scope.stats.loaded = true;
    });

My Test:

...
var STATS_RESPONSE_SUCCESS =
            {
                tankAvgHours:8,
                stillAvgHours:2,
                stillRemaining: 200,
                tankRemaining:50
            };
...

spyOn(tankService, "getCurrentStats").and.callThrough();

...

it('calls service and allocates stats with returned data', function () {

            expect($scope.stats.loaded).toBeFalsy();

            $httpBackend.whenPOST('../services/tanks/http://ift.tt/2cOR4sM').respond(200, $q.when(STATS_RESPONSE_SUCCESS));

            tankService.getCurrentStats()
                .then(function(res){
                    result = res.data.$$state.value;
                });

            $httpBackend.flush();


            expect($scope.stats.tankAvgHours).toEqual(result.tankAvgHours);
            expect($scope.stats.stillAvgHours).toEqual(result.stillAvgHours);
            expect($scope.stats.stillRemaining).toEqual(result.stillRemaining);
            expect($scope.stats.tankRemaining).toEqual(result.tankRemaining);
            expect($scope.stats.loaded).toBeTruthy();

        });

The result is that my scope variables are undefined and don't equal my mocked response data. Is it possible to pass the mocked values so I can test the success function correctly populates the variables?

Thanks!

Aucun commentaire:

Enregistrer un commentaire