我正在尝试测试一个代码,等待一个承诺之前调用http:
代码:function foo() {
return Parse.Promise.as(1).then(function(one) {
return $http.get('/bar');
});
}
测试:describe('foo', function() {
it('gets', function(done) {
$httpBackend.expect('GET', '/bar').respond(200);
foo().then(function(res) {
expect(res.status).to.be.equal(200);
done();
});
$httpBackend.flush();
});
});
错误:1) gets
foo
No pending request to flush !
我的猜测是,因为Parse.Promise
延迟了承诺解析,当$httpBackend.flush
被调用时,http请求没有发出。
有什么解决方法吗?
Mocha实际上有承诺语法支持,你可以直接通过去掉done
参数并返回承诺来测试承诺:
describe('foo', function() {
it('gets', function() { // no `done`
try {
$httpBackend.expect('GET', '/bar').respond(200);
return foo().then(function(res) { // return here
expect(res.status).to.be.equal(200);
});
} finally {
$httpBackend.flush();
}
});
});
默认情况下,Parse Promise延迟到下一个tick或timeout 0。
您可以在测试前调用Parse.Promise.disableAPlusCompliant();
禁用此行为。