user1493376 user1493376 - 3 months ago 9
Node.js Question

Test and stub params in POST request

Guys how can I stub params in POST request, for example here a part of function

gridCalculator : function(req,res){
// calculation logic
var options=[];
options.dateFirstLicensed = req.param('DateFirstLicensed');
options.dateFirstInsured = req.param('DateFirstInsured');
options.claimList = req.param('ClaimList');
options.suspenList = req.param('SuspenList');

...etc


if I did this

it('grid Calculate', function (done) {
var req = {
'DateFirstLicensed' : "01-01-2010",
'DateFirstInsured': "01-01-2011",
'ClaimList': ['05-03-2012'],
'SuspenList': [{'StartDate':'05-03-2012','EndDate':'05-05-2012' }]
};
gridCalculator.gridCalculator(req,function (err, result) {
result.should.exist;
done();
});
});


I get error because I'm simply passing an object not POST request

TypeError: req.param is not a function

Answer

Two options come to mind (there are probably a lot more):

Option 1: Define the param function yourself:

  it('grid Calculate', function (done) {
    var params = function(param) {
      switch (param) {
        case 'DateFirstLicensed':
          return "01-01-2010";
        case 'DateFirstInsured':
        ... //do the same for all params 
      }
    };
    var req = {
     param: params
    };
    gridCalculator.gridCalculator(req,function (err, result) {
      result.should.exist;
      done();
    });
  });

Option 2: Use tools like supertest to create calls to your server's endpoint.