【问题标题】:Testing promise callback in NodeJS with Mocha & Sinon使用 Mocha 和 Sinon 在 Node JS 中测试 promise 回调
【发布时间】:2013-09-06 01:05:17
【问题描述】:

我正在尝试测试一个返回承诺的方法调用,但是我遇到了麻烦。这在 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

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

【问题讨论】:

    标签: node.js unit-testing mocha.js sinon


    【解决方案1】:

    在注册期间不会调用 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 的功能,因为你的代码的唯一部分(数据库连接)被删除了。

    【讨论】:

      【解决方案2】:

      我建议查看Mocha As Promised

      它允许比尝试执行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-as-promised 现在已弃用。从 Mocha 1.18.0 开始,Mocha 已经内置了 Promise 支持!万岁!!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 1970-01-01
      • 2016-06-24
      • 2017-10-07
      • 2016-06-11
      • 1970-01-01
      • 2019-07-18
      相关资源
      最近更新 更多