这是我以前的问题的延伸:$httpBackend in AngularJs Jasmine unit test
在我的控制器中,启动时会调用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);
} );
答案 0 :(得分:4)
从我的评论中逐字逐句:
当您创建控制器时,它会调用'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);
});