Javascript AngularJS:$httpBackend.flush()之前需要摘要
我正试图弄清楚为什么我需要在我的Javascript AngularJS:$httpBackend.flush()之前需要摘要,javascript,angularjs,unit-testing,testing,jasmine,Javascript,Angularjs,Unit Testing,Testing,Jasmine,我正试图弄清楚为什么我需要在我的$httpBackend.flush()之前调用$rootScope.$digest(),才能通过测试 如果我没有,我会得到错误:没有等待刷新的请求 这是我的测试: it('should post a new task to the server', function() { $httpBackend.when('POST', $rootScope.serverRoot + '/task/create').respond({}); var cr
$httpBackend.flush()
之前调用$rootScope.$digest()
,才能通过测试
如果我没有,我会得到错误:没有等待刷新的请求代码>
这是我的测试:
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请求之前刷新该请求。$digetst()调用为它提供了执行异步工作的时间。正确的方法是(使用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”
请参见它可能是其他东西(您没有显示的东西),因为对我来说似乎是。我刚刚将您的确切代码复制到我的应用程序中。虽然我在使用因果报应,但这是我在复制我的代码时看到的唯一区别,它是否在没有$digest()
的情况下工作?不,不幸的是,它没有……我恐怕帮不上什么忙。这似乎是特定于设置和/或业力的。如果没有$digest()
,您是否已经指出了它失败的地方?例如,请求是否已发送?承诺解决了吗?