角模拟$ httpBackend给没有挂起请求刷新挂起、httpBackend

2023-09-13 04:30:16 作者:倾心与你

继 angularJS $ httpBackend官方指南我会做这个测试,但给噶我这个错误:错误:没有挂起请求刷新!        在功能。$ httpBackend.flush

Following the official guide at angularJS $httpBackend I'll do this test, but Karma give me this error: 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);

});

推荐答案

_ $ httpBackend _ 无关冲洗,因为你不使你的测试任何HTTP请求

The _$httpBackend_ has nothing to flush because you don't make any http request in your test.

您需要调用一些code,使一个HTTP请求。

You need to invoke some code that make an http request.

然后,一旦一些地方在您的测试做一个HTTP请求,则可以使提供给已提出请求的响应调用刷新方法。

Then, once something somewhere made an http request in your test, you can call the flush method so that a response is provided for the request that has been made.

是这样的:

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