0

I'm trying to test the response of an http call. The problem is, it passes no matter what response code I put in there or response data. Any ideas? Thanks!

Controller.js

$scope.getPresses = function() {
    var pressRequest = {
        method: 'GET',
        url: localAPI.url + 'press/',
        headers: requestHeaders
    };
    $http(pressRequest)
        .success(function(data) {
            $scope.userPresses = data.results;
        })
        .error(function() {
            alert("We were not able to retrieve your press data");
        });
};

testController.js

    describe('Get Presses', function() {
        it("sets scope attributes for the user's presses", function() {
            $scope.getPresses()
            $httpBackend.expectGET('http://0.0.0.0:8000/api/press/', function() {
                return {
                    Authorization: "Token fakeToken2903920932"
                }
            }).respond(304, 'responseData')
            $httpBackend.flush()
        });
    });
Peter Graham
  • 2,467
  • 2
  • 24
  • 29
  • 1
    You aren't testing anything other than that the request was made. You need to check the `$scope.userPresses` value for successful requests. I don't know how you're going to test an `alert` for the error state though. At the very least, you should inject `$window` and run `$window.alert` in your controller. Then you can mock `$window` in your test – Phil Feb 12 '15 at 22:33
  • @Phil I'm able to execute other tests (that aren't listed above) but when I put $httpBackend in the describe or it(), they don't get run as if they aren't there at all. – Peter Graham Feb 13 '15 at 21:30
  • Then show the rest of your code – Phil Feb 13 '15 at 23:46

1 Answers1

1

Ok, first, avoid global functions like alert. They are difficult to test. Instead, inject $window into your controller and use

$window.alert("We were not able to retrieve your press data");

Now, as for your test, you need to test the actual results. For example...

var $window, $scope, $httpBackend;

beforeEach(function() {
    module('your.module', function($provide) {
        $provide.value('$window', $window = jasmine.createSpyObj('$window', ['alert']));
    });

    // and however else you set up your $scope and $httpBackend vars
});

it('assigns results to userPresses on success', function() {
    $httpBackend.expectGET('http://0.0.0.0:8000/api/press/', function(headers) {
        return headers['Authorization'] === 'Token fakeToken2903920932';
    }).respond({results: 'results'});

    $scope.getPresses();
    $httpBackend.flush();

    expect($scope.userPresses).toBe('results');
});

it('calls alert on error', function() {
    $httpBackend.whenGet('http://0.0.0.0:8000/api/press/').respond(500);
    $scope.getPresses();
    $httpBackend.flush();

    expect($window.alert).toHaveBeenCalled();
});
Phil
  • 157,677
  • 23
  • 242
  • 245