如何验证根本没有发出http请求?

Ade*_*lin 6 angularjs

如何验证没有调用任何http请求方法来执行任何请求.我有这个代码:

 $scope.getSubnetsPageDetails = function (pageNumber) {
        $http.get(URLS.subnetsPagesCount(pageNumber)).success(function (response) {
            $scope.pageDetails = response;
        }).error(function (response, errorCode) {

            });
    }; 
Run Code Online (Sandbox Code Playgroud)

而这个测试:

it("should not allow request with negative page number", function () {

        scope.getSubnetsPageDetails(-1);
        //verify that htt.get is not invoked at all

    });
Run Code Online (Sandbox Code Playgroud)

如何验证未调用http.get?

pko*_*rce 13

您可以使用$ httpBackend mock中verifyNoOutstandingRequest()方法测试没有进行调用.

通常这些验证是在afterEachJasmine的测试部分完成的.除此之外,通常调用另一个方法verifyNoOutstandingExpectation()来验证是否实际调用了所有预期的调用.

这是代码,您需要注入$httpBackend模拟:

var $httpBackend;
beforeEach(inject(function($injector) {
  $httpBackend = $injector.get('$httpBackend');
}));
Run Code Online (Sandbox Code Playgroud)

然后你测试,最后:

afterEach(function() {
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});
Run Code Online (Sandbox Code Playgroud)

当然你可以调用$httpBackend.verifyNoOutstandingRequest()内部的单个测试.上面提到的http://docs.angularjs.org/api/ngMock.$httpBackend页面提供了有关该主题的大量信息.