【问题标题】:Unable to have sinon spy called in the context of a mocha test with method that calls method with promises无法在 mocha 测试的上下文中调用 sinon 间谍,方法是调用带有承诺的方法
【发布时间】:2016-05-22 08:21:06
【问题描述】:

我有一个模块调用一个使用 bluebird 承诺的方法。这是简化的模块。 Cassandra 只是对一些承诺它们的数据库调用的包装器:

var Cassandra = require('../lib/cassandraObject');
var cassandra = new Cassandra();
exports.doIt = function _doIt(req, res) {
    cassandra.queryPromise("query", [1, 2, 3])
    .then(function (results) {
        res.sendStatus(200);
     })
    .catch(function(er) {
        res.sendStatus(500);
    })
}

我正在尝试用 sinon 和 sinon-bluebird 对此进行测试。我存根调用 Cassandra 的查询承诺,并将 res.sendStatus 设为间谍:

   it("makes a call to doIt", function () {
        var qpMock = sinon.stub(Cassandra.prototype, "queryPromise").resolves(['yay!']);
        var req = {};
        var res = {
            sendStatus: sinon.spy(),
        };
        myModule.doIt(req, res);
        expect(qpMock.args[0][1][0]).to.equal(1);   //ok
        expect(res.sendStatus).to.have.been.calledWith(200);  //error ! not called yet!
    }

我认为使用这些库,存根的 then() 会立即被调用,而不是异步调用,但事实似乎并非如此。 res.sendStatus() 调用确实被调用,但在测试超出范围之后。

有什么方法可以知道 res.sendStatus() 何时被调用并将其保留在测试范围内,以便我可以断言传递给它的值?

【问题讨论】:

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


    【解决方案1】:

    我建议让doIt() 可链接,通过让它返回承诺:

    exports.doIt = function _doIt(req, res) {
        return cassandra.queryPromise("query", [1, 2, 3])
                        .then(function (results) {
                          res.sendStatus(200);
                        })
                        .catch(function(er) {
                          res.sendStatus(500);
                        })
    }
    

    这样,您可以在测试用例中等待完成,以便在确定已调用 res.sendStatus() 时检查它。

    此外,由于 Mocha 支持开箱即用的 Promise,您可以从 doIt() 返回 Promise,以确保 Mocha 等待您的测试完全完成后再继续:

    it("makes a call to doIt", function () {
      var qpMock = sinon.stub(Cassandra.prototype, "queryPromise").resolves(['yay!']);
      var req = {};
      var res = { sendStatus: sinon.spy() };
      return myModule.doIt(req, res).then(() => {
        expect(qpMock.args[0][1][0]).to.equal(1); 
        expect(res.sendStatus).to.have.been.calledWith(200);
      });
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-24
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-21
      相关资源
      最近更新 更多