我想弄清楚为什么我需要在 $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,它会在异步代码有机会发出该请求之前尝试 flush() $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”
参见 http://jasmine.github.io/2.0/introduction.html#section-Asynchronous_Support
关于javascript - AngularJS:在 $httpBackend.flush() 之前需要 $digest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23971518/