AngularJS:在$httpBackend.flush()之前需要$digest

AngularJS: $digest required before $httpBackend.flush()

本文关键字:digest httpBackend flush AngularJS      更新时间:2023-09-26

我正试图理解为什么我需要在$httpBackend.flush()之前调用$rootScope.$digest()以使我的测试通过。

如果我不这样做,我将得到Error: No pending request to flush!

下面是我的测试:

it('should post a new task to the server', function() {
    $httpBackend.when('POST', $rootScope.serverRoot + '/task/create').respond({});
    var created = false;
    mockBoardService.addTask({name: 'Add dynamic categories'})
        .then(function(response) {
            created = true;
        }
    );
    $rootScope.$digest();
    $httpBackend.flush();
    expect(created).toBe(true);
})

和它正在调用的服务函数:

this.addTask = function(data) {
    return $http.post($rootScope.serverRoot + '/task/create', data);            
}

为什么需要运行$rootScope.$digest

看起来像是mockBoardService。addTask正在执行一些异步工作。如果没有$digest,它会在异步代码有机会发出该请求之前尝试刷新()$httpBackend请求。$ digest()调用给了它时间来完成异步工作。正确的方法(在Jasmine 2.0中,在1.3中略有不同)是这样做的:

it('should post a new task to the server', function(done) {
    $httpBackend.when('POST', $rootScope.serverRoot + '/task/create').respond({});
    var created = false;
    mockBoardService.addTask({name: 'Add dynamic categories'})
        .then(function(response) {
            created = true;
            done();
        }
    );
    $httpBackend.flush();
    expect(created).toBe(true);
})

注意'it'中传递给函数的'done'

看到http://jasmine.github.io/2.0/introduction.html section-Asynchronous_Support