【发布时间】:2015-12-01 10:04:11
【问题描述】:
我想使用mocha、chai 和sinon 测试我的承诺解析处理程序和承诺拒绝处理程序。此外,我已经设置了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)
【问题讨论】:
-
存根 promise 是否同步?
-
实现是
thenable,它可以与任何具有then的东西链接在一起,包括我不想做的真正的承诺,所以我使用@ 987654332@ 和rejects仅测试处理程序。我在观看this video 之后尝试了这个,他在其中捕获了 jQuery ajax 成功回调的参数, -
是的,我只是想知道您希望处理程序在您附加它们之后立即被调用。正常的承诺会失败。
标签: javascript promise mocha.js sinon sinon-chai