我想使用mocha
,chai
和sinon
来测试我的承诺解析处理程序并承诺拒绝处理程序。此外,我有sinon-chai
插件和{ {1}}插件设置。
这是我的需求声明块:
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();
});
});
答案 0 :(得分:0)
sinon-with-promise套餐应该适合您尝试做的事情。我遇到了同样的问题(除了我不需要测试拒绝案例)并且效果很好。
答案 1 :(得分:-1)
这行代码错误:
expect(resolveHandler).to.have.been.called();
called
只是spy上的一个属性,其值始终为boolean
,可以使用chai
进行简单测试,如下所示:
expect(resolveHandler.called).to.equal(true);
同样代替此行来确认函数未被拒绝:
expect(rejectHandler).to.have.not.been.called();
将called
用作财产:
expect(rejectHandler.called).to.equal(false);