user1493376
user1493376

Reputation: 123

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

Upvotes: 1

Views: 63

Answers (2)

Vincent Schöttke
Vincent Schöttke

Reputation: 4716

The problem is that you don't stub the function that is used in your gridCalculator method in your test.

It should look like this:

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

Upvotes: 0

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

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.

Upvotes: 1

Related Questions