2015-09-05 78 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包应该适合你要做的事情。我遇到了同样的问题(除了我不需要测试拒绝情况),它很好地解决了问题。