繁体   English   中英

与Mocha和Sinon间谍一起测试Express.js res.render的承诺

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

继一个类似的模式,以这个例子 ,我一直在尝试测试在Express.js应用我的路线,但我不能让我的间谍,以验证res.render包裹在当被称为promise.then

这是一个简化的示例,我希望calledOnce为true,但返回的是false。

被测代码:

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本机支持诺言,因此您可以设置代码以将原始诺言一路传递回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;
    });
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM