Unit test crash when calling function at startup

This is an extension of my previous question: $ httpBackend in AngularJs Jasmine unit test

In my controller, the getStuff function is called at startup. This causes my unit test to crash. When I comment on this, my unit tests pass and work successfully. When commenting out the error:

Error: Unexpected request: GET / api / stuff No more expectations expected

My controller:

$scope.stuff = []; $scope.getStuff = function () { var url = site.root + 'api/stuff'; $http.get(url) .success(function (data) { $scope.stuff = data; }) .error(function(error) { console.log(error); }); }; //$scope.getStuff(); 

and my unit test:

 it('should get stuff', function () { var url = '/api/stuff'; var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }]; httpLocalBackend.expectGET(url).respond(200, httpResponse); $scope.getStuff(); httpLocalBackend.flush(); expect($scope.stuff.length).toBe(2); } ); 

All unit test wisely, works great. Unfortunately, this violates the actual functionality of the site. When I uncomment the last line of the controller, the unit test breaks and the site works. Any help is appreciated. Thanks!

FIXED: thanks to fiskers7 answer this is my solution.

 it('should get stuff', function () { var url = '/api/stuff'; var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }]; httpLocalBackend.expectGET(url).respond(200, httpResponse); httpLocalBackend.expectGET(url).respond(200, httpResponse); $scope.getStuff(); httpLocalBackend.flush(); expect($scope.stuff.length).toBe(2); } ); 
+1
javascript angularjs unit-testing jasmine
source share
1 answer

Verbatim from my comment:

When you create a controller, it calls the api / stuff call, and when you call $ scope.getStuff () in your test, you call it again. Therefore, instead of a single call to api / stuff, you have two, which indicates an error. httpBackend did not expect two endpoint calls, only one, so it throws an error.

Sample code from my comment on this answer if you need to see it.

 it('should get stuff', function () { var url = '/api/stuff'; var httpResponse = [{ "stuffId": 1 }, { "stuffId": 2 }]; httpLocalBackend.expectGET(url).respond(200, httpResponse); httpLocalBackend.flush(); expect($scope.stuff.length).toBe(2); }); 
+4
source share

All Articles