Unit test failing when function called on startup

醉酒当歌 提交于 2019-12-08 03:15:21

问题


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);
} );

回答1:


Verbatim from my comment:

When you create the controller it makes a call to 'api/stuff' and when you call $scope.getStuff() in your test you call it again. So instead of one call to 'api/stuff' you have two which is what the error is saying. httpBackend didn't expect two calls to the endpoint, only one so it throws the error.

Code example from my comment to 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); 
});


来源:https://stackoverflow.com/questions/25794501/unit-test-failing-when-function-called-on-startup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!