我想使用mocha,chai和sinon.In测试我的promise resolve处理器和promise rejection处理器,另外,我已经设置了sinon-chai插件和sinon-stub-promise插件。
这是我的require语句块:
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)发布于 2017-05-29 22:08:37
sinon-with-promise包应该符合您想要做的事情。我遇到了同样的问题(除了我不需要测试拒绝用例),它很好地解决了。
发布于 2015-09-05 19:11:30
这里的这行代码是错误的:
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);https://stackoverflow.com/questions/32411734
复制相似问题