簡體   English   中英

與Chai和Sinon一起測試承諾的服務

[英]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()是異步的,則您需要等待其完成之后才能檢查您的斷言;
  • 由於(建議的)解決方案會檢查Promise處理程序中的斷言,因此您必須小心例外。 與其使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM