如何测试在Jasmine中发送到服务器的请求数

时间:2014-04-07 09:18:37

标签: angularjs testing jasmine

有谁知道我如何测试使用Jasmine $ httpBackend对象发送了多少请求?

我有一个使用从RESTful服务获得的数据构建的kendo网格。

网格还具有预过滤功能。这意味着您可以声明一组条件,然后在构建网格时,将条件与数据请求一起发送到服务器。

然后,在发送响应之前,RESTful服务应该过滤数据。因此,响应将仅包含符合条件的数据。

问题是目前正在发送两个请求:一个用于数据,另一个用于标准。

我想编写一个测试,确保只发送一个请求,原始数据,以及过滤由RESTful服务完成。

这是我的测试:

it('should send only one request to the server when getting data to build the grid', function () {
    angular.mock.inject(function ($compile, $rootScope) {
        var scope = $rootScope.$new();

        // THE CRITERIA
        scope.myCriteria = {
            "operator": "and",
            "operands": [
                {
                    "property": "accountId",
                    "value": "1",
                    "constraint": "contains",
                    "ignoreCase": "true"
                }
            ]
        };

        // THE ORIGINAL DATA
        var respondData = [
            {accountId: '1', name: 'Account 1', status: 'active'},
            {accountId: '3', name: 'Account 3', status: 'active'},
            {accountId: '4', name: 'Account 4', status: 'active'}
        ];

        // THE REQUEST TO GET THE DATA
        $httpBackend.when('GET', "api/grid/accounts?crit=substringof('1',accountId)+eq+true").respond(respondData);

        // BUILD THE GRID 
        // sg-data is the data from the RESTful service. 
        // sg-filters is the filtering criteria
        var elem = $compile('<div sg-grid sg-data="api/grid/accounts" sg-columns="accountId,name,shortName,status" sg-filters="myCriteria"></div>')(scope);

        $rootScope.$apply();
        $httpBackend.flush();
        /*
         I want to do something like this:
         expect($httpBackend.requests.length).toBe(1);
        */
    });
});

1 个答案:

答案 0 :(得分:3)

您应该使用expect而不是when,因为您想断言发送了哪些请求。

$httpBackend.expect('GET', "api/grid/accounts?crit=substringof('1',accountId)+eq+true").respond(respondData);
...
$httpBackend.flush();
...
$httpBackend.verifyNoOutstandingExpectation();    

最后一行验证代码是否发出了第一个请求。使用expect代替when,我们会验证是否未发出第二个请求。如果代码会发出第二个请求,那么您将收到“不再需要请求”错误。

他们描述了AngularJS docs

中请求期望($httpBackend.expect)和后端定义($httpBackend.when)之间的差异
  

要求期望   提供一种方法来对关于请求的请求进行断言   应用程序并定义这些请求的响应。测试会   如果没有做出预期的请求或者在预期请求中发出请求,则会失败   错误的订单。

     

后端定义允许您为您的后端定义假后端   如果提出特定请求或不提出声明的应用程序   不是,如果提出请求,它只返回训练有素的响应。考试   无论是否在测试期间提出请求,都会通过。