【问题标题】:Testing Express.js res.render within promise with Mocha & Sinon spy使用 Mocha 和 Sinon spy 测试 Express.js res.render
【发布时间】:2016-02-24 08:41:48
【问题描述】:

遵循与this example 类似的模式我一直在尝试在 Express.js 应用程序中测试我的路由,但我无法让我的间谍验证 res.render 在包裹在 @987654323 中时是否已被调用@。

这是一个简化的示例,我希望 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;
  });
});

【问题讨论】:

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


    【解决方案1】:

    你必须等待 promise 得到解决,这是一个异步操作。

    由于 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;
        });
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-01
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多