Angular mock $ httpBackend给出没有待处理的请求

时间:2014-03-06 13:36:09

标签: angularjs karma-jasmine

按照angularJS $httpBackend的官方指南,我会做这个测试,但是Karma给了我错误Error: No pending request to flush ! at Function.$httpBackend.flush

测试

'use strict';

describe('profileCtrl', function () {
var scope, $httpBackend;

beforeEach(angular.mock.module('maap'));
beforeEach(angular.mock.inject(function($rootScope, $controller, _$httpBackend_){

    $httpBackend = _$httpBackend_;
    $httpBackend.when('GET', 'profile').respond([{id: 1, name: 'Bob'}]);
    scope = $rootScope.$new();
    $controller('profileCtrl', {$scope: scope});
}))

it('should fetch list of users', function(){
    $httpBackend.flush();
    expectGET(scope.current_user.length).toBe(1);
    expect(scope.current_user[0].name).toBe('Bob');
});

});

这个简单的控制器

'use strict';

 angular.module('maap').controller('profileCtrl', function($scope, UserService) {

$scope.current_user = UserService.details(0);

});

4 个答案:

答案 0 :(得分:29)

_$httpBackend_无需刷新,因为您未在测试中发出任何http请求。

您需要调用一些发出http请求的代码。

然后,一旦某个地方的某个地方在您的测试中发出了http请求,您就可以调用flush方法,以便为已发出的请求提供响应。

类似的东西:

it('should fetch list of users', function(){

    // Do something that will make an http request
    MyService.getAllUser(function ...) // for example

    // Then provide a response for the http request that 
    // has been made when getAllUser was called
    $httpBackend.flush();

    // Check the expected result.
    expect(something).toBe('Bob');
});

答案 1 :(得分:10)

同样的问题发生在我身上,问题不在于我没有提出请求,而是因为我提出的请求与预期的请求不同:

例如,我已经定义了这个期望:

mockBackend.expectGET("http://myapi.com/001").respond("RESULT");

我正在请求其他网址:

http://myapi.com/002

非常令人困惑的错误消息,与下面的问题无关。

答案 2 :(得分:0)

我有同样的例外,因为我使用了ngMockE2E模块而不是ngMock模块。甚至调用$ rootScope。$ digest()也没有帮助。

答案 3 :(得分:0)

也许您没有在 ajax 调用中使用 $http angularJs 服务

我碰巧在我期望 $httpBackend 刷新某些东西的地方,但我得到了

Error: No pending request to flush !

所以经过长时间的调查我发现ajax是用jQuerey而不是$http编写的

<块引用>

所以请确保您使用 $http 服务作为您的 Ajax calls

相关问题