我正在尝试测试一个返回 promise 的方法调用,但是我遇到了麻烦。这在 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('[{"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
测试返回 promise 的方法的正确方法是什么?
最佳答案
then() 调用的处理程序不会在注册期间调用 - 仅在下一个事件循环期间调用,它在当前测试堆栈之外。
您必须从完成处理程序中执行检查并通知 mocha 您的异步代码已完成。 另见 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);
});
});
对原始代码的更改:
- 测试函数的done参数
- 在 then() 处理程序中检查和清理
编辑:此外,老实说,此测试并未测试与您的代码有关的任何内容,它仅验证 promise 的功能,因为您的代码(数据库连接)的唯一部分被删除了。
关于node.js - 使用 Mocha 和 Sinon 在 Node JS 中测试 promise 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18581394/