在Mocha&Sinon的NodeJS中testing诺言callback

我试图testing一个方法调用返回一个承诺,但我有麻烦。 这在NodeJS代码中,我正在使用Mocha,Chai和Sinon来运行testing。 我现在的testing是:

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(); }); 

然而这个testing是错误的:

 AssertionError: expected spy to have been called exactly once, but it was called 0 times 

testing返回承诺的方法的正确方法是什么?

then()调用的处理程序在注册期间不会被调用 – 只在下一个事件循环期间,这是在当前的testing栈之外。

您必须在完成处理程序中执行检查,并通知摩卡您的asynchronous代码已经完成。 另见http://visionmedia.github.io/mocha/#asynchronous-code

它应该看起来像这样:

 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); }); }); 

对原始代码的更改:

  • 完成testingfunction的参数
  • 然后在()处理程序中检查和清理

编辑:另外,说实话,这个testing没有testing任何关于你的代码,它只是validation承诺的function,因为你的代码(数据库连接)的唯一部分被剔除。

我build议检查摩卡如承诺

它允许比尝试执行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}]'); }); });