This is an extension off a former question of mine: $httpBackend in AngularJs Jasmine unit test
In my controller, the getStuff function is called on startup. This causes my unit test to fail. When I comment it out, my unit tests pass and work successfully. When uncommented, the error is:
Error: Unexpected request: GET /api/stuff No more request expected
My controller is:
$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 is:
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);
} );
Everything unit test wise, works fine like this. Unfortunately, this breaks the actual site functionality. 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's 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);
} );