繁体   English   中英

启动时调用函数时单元测试失败

[英]Unit test failing when function called on startup

这是我以前的问题的扩展: AngularJs Jasmine单元测试中的$ httpBackend

在我的控制器中,getStuff函数在启动时被调用。 这导致我的单元测试失败。 当我注释掉时,我的单元测试通过并成功工作。 取消注释时,错误为:

错误:意外请求:GET / api / stuff预期没有其他请求

我的控制器是:

$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();

我的单元测试是:

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

一切单元测试明智,像这样正常工作。 不幸的是,这破坏了实际的站点功能。 当我取消注释控制器的最后一行时,单元测试将中断,并且该站点可以正常工作。 任何帮助表示赞赏。 谢谢!

修正:感谢fiskers7的回答,这是我的解决方案。

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

我的逐字记录:

创建控制器时,它将调用“ api / stuff”,而在测试中调用$ scope.getStuff()时,将再次调用它。 因此,不是一个对“ api / stuff”的调用,而是两个,这就是错误的意思。 httpBackend预期不会有两次对端点的调用,只有一次会因此引发错误。

如果需要查看我的评论的代码示例,请参见此答案。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM