2015-09-05 33 views
2

我想測試我的承諾的決心處理程序,並允許用戶使用mochachaisinon。此外排斥處理器的承諾,我已經得到了sinon-chai插件和插件sinon-stub-promise成立。測試與摩卡薛寶釵和興農

這是我需要的語句塊:

var chai = require('chai'); 
var expect = chai.expect; 
var sinonChai = require('sinon-chai'); 
chai.use(sinonChai); 
var sinon = require('sinon'); 
var sinonStubPromise = require('sinon-stub-promise'); 
sinonStubPromise(sinon); 

這是我的測試套件:

describe('Connect to github users',function(done){ 

    var api = require('../users'), 
     onSuccess = api.onSuccess, 
     onError = api.onReject; 
    console.dir(api); 
    //the idea is not to test the async connection,the idea is to test 
    //async connection but to test how the results are handled. 
    var resolveHandler, 
     rejectHandler, 
     getPromise, 
     result; 

    beforeEach(function(){ 
     resolveHandler = sinon.spy(onSuccess); 
     rejectHandler = sinon.spy(onError); 
     getPromise = sinon.stub().returnsPromise(); 
    }); 

    it('must obtain the result when promise is successful',function(){ 
     result = [...];//is an actual JSON array  
     getPromise.resolves(result); 

     getPromise() 
      .then(resolveHandler) 
      .catch(rejectHandler); 

     expect(resolveHandler).to.have.been.called();//error 
     expect(resolveHandler).to.have.returned(result); 
     expect(rejectHandler).to.have.not.been.called();  
     done(); 
    }); 

    afterEach(function(){ 
     resolveHandler.reset(); 
     rejectHandler.reset(); 
     getPromise.restore(); 
    }); 

}); 

我發現自己收到此錯誤:

Connect to github users must obtain the result when promise is successful: 
TypeError: expect(...).to.have.been.called.toEqual is not a function 
    at Context.<anonymous> (C:\Users\vamsi\Do\testing_promises\test\githubUsersSpec.js:94:46) 
+0

存根承諾同步嗎? – Bergi

+0

這個實現是一個'thenable',它可以與任何具有'then'的任何東西鏈接在一起,包括*真實承諾*,我不想這麼做,所以我使用'resolves'和'rejects'來測試一個處理程序。我在觀看[這段視頻](https://youtu.be/HHcEjAQ46Io?t=2213)後試圖獲取jQuery ajax成功回調的參數, – vamsiampolu

+0

是的,我只是想知道你希望處理程序被調用的權利你有他們連接後。正常的承諾會失敗。 – Bergi

回答

-1

這行代碼這裏是錯誤的:

expect(resolveHandler).to.have.been.called(); 

called只是在其值始終是一個boolean並且可以使用chai這樣簡單地測試spy屬性:

expect(resolveHandler.called).to.equal(true); 

類似的,而不是這條線,以確認該功能沒有拒絕:

expect(rejectHandler).to.have.not.been.called(); 

called使用此作爲一個屬性:

expect(rejectHandler.called).to.equal(false); 
+1

代碼沒有錯,他試圖使用'sinon-chai',因此'to.have.been.called'是有效的代碼。 –

0

sinon-with-promise包應該適合你要做的事情。我遇到了同樣的問題(除了我不需要測試拒絕情況),它很好地解決了問題。