[英]testing promised service with Chai and Sinon
我一直在柴和錫南(Sinan)測試測試。 通常我得到的服務是xhr請求的包裝器,它返回promise。 我試圖像這樣測試它:
beforeEach(function() {
server = sinon.fakeServer.create();
});
afterEach(function() {
server.restore();
});
describe('task name', function() {
it('should respond with promise error callback', function(done) {
var spy1 = sinon.spy();
var spy2 = sinon.spy();
service.get('/someBadUrl').then(spy1, spy2);
server.respond();
done();
expect(spy2.calledOnce).to.be.true;
expect(sp2.args[0][1].response.to.equal({status: 404, text: 'Not Found'});
});
});
我對此的注意事項:
//在期望完成斷言之后調用spy2
//嘗試使用var timer = sinon.useFakeTimers()
和timer.tick(510);
沒有結果
//嘗試使用chai-as-promised-不知道如何使用它:-(
//無法安裝我的環境中僅可用的sinon-as-promised
選定的npm模塊
任何想法如何解決此代碼/測試此服務模塊?
這里有各種挑戰:
service.get()
是異步的,則您需要等待其完成之后才能檢查您的斷言; done()
,不如選擇使用Mocha(我假設您正在使用)內置的Promise支持。 嘗試這個:
it('should respond with promise error callback', function() {
var spy1 = sinon.spy();
var spy2 = sinon.spy();
// Insert the spies as resolve/reject handlers for the `.get()` call,
// and add another .then() to wait for full completion.
var result = service.get('/someBadUrl').then(spy1, spy2).then(function() {
expect(spy2.calledOnce).to.be.true;
expect(spy2.args[0][1].response.to.equal({status: 404, text: 'Not Found'}));
});
// Make the server respond.
server.respond();
// Return the result promise.
return result;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.