Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用Mocha&;在NodeJS中测试promise回调;西农_Node.js_Unit Testing_Mocha.js_Sinon - Fatal编程技术网

Node.js 使用Mocha&;在NodeJS中测试promise回调;西农

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

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

在注册期间将不会调用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支持!好极了