2016-07-02 19 views
1

我試圖測試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請求。

有沒有解決方法?

回答

0

默認情況下解析承諾delays to the next tick or with timeout 0

您可以在測試之前禁用此行爲調用Parse.Promise.disableAPlusCompliant();

+0

這會破壞你的代碼的執行順序,你可能會得到莫名其妙的故障。 –

+0

只有在需要時纔可以禁用單個測試。這是我搜索數小時後才能使其工作的唯一途徑。 – gfpacheco

1

摩卡其實是有前途語法的支持,你可以通過刪除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(); 
    } 
    }); 
}); 
+0

但是你必須調用'$ httpBackend.flush'才能解決'$ http.get'的承諾。你什麼時候可以這樣做? – gfpacheco

+0

@gfpacheco哦對,你需要打電話,因爲你嘲笑httpBackend,lemme修改 –

+0

對不起,仍然沒有爲我工作。你測試過了嗎? – gfpacheco