测试Express.js res.render在承诺与Mocha&Sinon spy

Testing Express.js res.render within promise with Mocha & Sinon spy

本文关键字:Mocha amp spy Sinon 承诺 js Express res render 测试      更新时间:2023-09-26

按照与此示例类似的模式,我一直在尝试在 Express.js 应用程序中测试我的路由,但我无法让我的间谍验证res.render在包装在promise.then中时是否已被调用。

这是一个简化的示例,我希望calledOnce为真,但它返回为假。

测试中的代码:

var model = {
  get: function() {
    return new Promise(function(res, rej) {
      return res('success');
    });
  }
};
module.exports = function (req, res) {
  model.get().then(function (data) {
    res.render('home', data);
  }).catch(function (err) {
    console.log(err);
  });
};

测试:

var expect = require('chai').expect;
var sinon = require('sinon');
var home = require('./home');
describe('home route', function() {
  it('should return a rendered response', function() {
    var req = {};
    var res = {
      render: sinon.spy()
    };
    home(req, res);
    expect(res.render.calledOnce).to.be.true;
  });
});

您必须等待承诺得到解决,这是一个异步操作。

由于 Mocha 原生支持 promise,因此您可以设置代码以将原始 promise 一直传递回 Mocha,并在链中插入一个测试用例:

// home.js
...
module.exports = function (req, res) {
  // return the promise here
  return model.get().then(function (data) {
    res.render('home', data);
  }).catch(function (err) {
    console.log(err);
  });
};
// test.js
describe('home route', function() {
  it('should return a rendered response', function() {
    var req = {};
    var res = { render: sinon.spy() };
    // Also return the promise here, and add an assertion to the chain.
    return home(req, res).then(function() {
      expect(res.render.calledOnce).to.be.true;
    });
  });
});