Node.js 使用Mocha&;在NodeJS中测试promise回调;西农
我正在尝试测试一个返回承诺的方法调用,但遇到了问题。这是NodeJS代码,我使用Mocha、Chai和Sinon来运行测试。我目前的测试是:Node.js 使用Mocha&;在NodeJS中测试promise回调;西农,node.js,unit-testing,mocha.js,sinon,Node.js,Unit Testing,Mocha.js,Sinon,我正在尝试测试一个返回承诺的方法调用,但遇到了问题。这是NodeJS代码,我使用Mocha、Chai和Sinon来运行测试。我目前的测试是: it('should execute promise\'s success callback', function() { var successSpy = sinon.spy(); mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve
it('should execute promise\'s success callback', function() {
var successSpy = sinon.spy();
mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));
databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(successSpy, function(){});
chai.expect(successSpy).to.be.calledOnce;
databaseConnection.execute.restore();
});
但是,该测试存在以下错误:
AssertionError: expected spy to have been called exactly once, but it was called 0 times
测试返回承诺的方法的正确方法是什么?在注册期间将不会调用then()调用的处理程序-仅在当前测试堆栈之外的下一个事件循环期间调用
您必须从完成处理程序中执行检查,并通知mocha您的异步代码已经完成。
另见
它应该是这样的:
it('should execute promise\'s success callback', function(done) {
mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));
databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(function(result){
chai.expect(result).to.be.equal('[{"id":2}]');
databaseConnection.execute.restore();
done();
}, function(err) {
done(err);
});
});
对原始代码的更改:
- 测试函数的done参数
- 在then()处理程序中检查并清除
done()
和所有这些废话更干净的语法
it('should execute promise\'s success callback', function() {
var successSpy = sinon.spy();
mySpies.executeQuery = sinon.stub(databaseConnection, 'execute').returns(q.resolve('[{"id":2}]'));
// Return the promise that your assertions will wait on
return databaseConnection.execute('SELECT 2 as id FROM Users ORDER BY RAND() LIMIT 1').then(function() {
// Your assertions
expect(result).to.be.equal('[{"id":2}]');
});
});
正如承诺的那样,摩卡咖啡现在已经被弃用了。从Mocha 1.18.0开始,Mocha具有内置的promise支持!好极了