如何测试表达中间件摩卡

时间:2016-11-20 20:48:05

标签: node.js express mocha

var _ = require('lodash');

exports = function(restype, opt) {
  return function(req, res) {
    //if restype is 'send', it's sends like an api
    //else it renders something
    if (restype == 'send') {

      if (req.result.status == 'error') res.status(500).send(req.result);
      else res.send(req.result);

    } else {

            var options = _.merge(opt,req.result);
      if (req.result.status == 'error') res.render('error', options);
      else res.render(restype, options);

    }
  };
};

但我不知道如何设置req,res,restype和opt。 并测试它(检查何时调用res.render或res.send。

1 个答案:

答案 0 :(得分:0)

因此,对于更大规模的测试,引入像Sinon这样的模拟库是有用的。但是如果你只依赖自己的代码(如本例所示)那么你可以传递你需要的东西。如果不完整(您需要添加其他需要的方法)示例:

const assert = require('assert');

describe('when restype is send', () => {
  const middleware = require('../path/to/your/file');
  function renderMock(type, opts){
      // this should not be called
      assert(false, 'RenderMock should not be called');
  }

  const request = {result: {}}; // add stuff you need there

  it ('should call res.send', () => {
     let sendWasCalled = false;
     const response = {render: renderMock, send: function(){ /* you might validate inputs here */  sendWasCalled = true; };
     middleware('send', {})(request, response);
     assert(sendWasCalled, 'res.send should have been called');
  });
});