我正在测试轮询资源的序列,直到满足条件。
Book = $resource("/books/:id", {id: "@id"});
function poll(success) {
Book.get({id:1}, function() {
if (canStop) {
success();
} else {
$timeout(poll, 1000);
}
});
};
以下测试因Error: Unsatisfied requests: GET /user_workshops/1
describe('poll', function() {
beforeEach(function() {
$httpBackend.expectGET('/books/1').respond(200,{id:1});
$httpBackend.expectGET('/books/1').respond(200,{id:1, newVal:1});
poll(function() {
successCalled = true;
});
$httpBackend.flush();
$timeout.flush();
canStop=true;
$httpBackend.flush();
});
it('should call success when canStop is true', function() {
expect(successCalled).toBe(true);
});
});
我尝试重新排列测试订单,将第二个expectGET
放在第二个httpBackend.flush()
之前,但后来我得到了:
Error: Unexpected request: POST /books/1
No more request expected
答案 0 :(得分:10)
经过一个小时的拔毛后,我意识到httpBackend是非常特定于测试被调用的顺序 - 期望必须不是在调用flush之前设置,而是在资源请求之前设置已经完成,当你打电话时,你必须完全准确地做出预期的请求。
这意味着如果要在顺序请求之间进行刷新,请求和期望的顺序必须完全符合:
$httpBackend.expectGET('...')
resource.get();
$httpBackend.flush()
$httpBackend.expectGET('...')
resource.get();
$httpBackend.flush()
...
etc
所以在上面代码的情况下,如果我将排序更改为:
,它就有效describe('poll', function() {
beforeEach(function() {
$httpBackend.expectGET('/books/1').respond(200,{id:1});
poll(function() {
successCalled = true;
});
$httpBackend.flush();
$httpBackend.expectGET('/books/1').respond(200,{id:1, newVal:1});
$timeout.flush();
canStop=true;
$httpBackend.flush();
});
it('should call success when canStop is true', function() {
expect(successCalled).toBe(true);
});
});
答案 1 :(得分:0)
您还可以在每次通话时重新安装$ httpBackend方法。有点像:
var deleteMethod = function () {
$httpBackend.when('DELETE', /.*/gi).respond(function(method, url, data) {
deleteMethod(); // <--- See here method is rearmed
return [200, 'OK', {}];
});
}
deleteMethod();