2016-11-20 17 views
0
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的調用時間)如何測試特快中間件摩卡

回答

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'); 
    }); 
});