Thursday, 11 May 2017

Need help authenticating my mocha/chai tests when testing routes

Here is my route I'm trying to test: (I realize this is more of a get then a post, will fix that soon, currently out of my control)

router.post('/participant-roles', function(req, res) {
var sid = req.body.scenarioId;
var query = 'SELECT "userId", "scenarioRoleId" FROM "Scenario_Roles_Users" WHERE "isActive" = 1 AND "scenarioId" = '+sid+' ORDER BY "userId", "scenarioRoleId"';
sequelize.query(query).then(function(userRoles) {
  res.send(userRoles[0]);
});

Here is my mocha/chai test case:

describe("temp", function(done){
// This test when there is only 1 condition for a given scenario
it('temp', function(done) {
chai.request(server)
    .post('/viewer/participant-roles')
    .send({"scenarioId": 22,"isAuthenticated": true})
    .end(function(err, res) {
      expect(res).to.have.status(200);
      console.log(res.body);
      done();
    });
});

This code works perfectly fine. However, when I introduce the authentication snippet below (this snippet is found at the top of my route code) my test no longer works because my test is not authenticated.

var isAuthenticated = function (req, res, next) {
   if(req.isAuthenticated()){
      return next();
   }
   res.redirect('/');
};

So in my current situation I have to comment out the authentication code in the routes in order for the test to give me the information I need. (My unit test is not finished by the way, just simply trying to get it to return my res.body information before I finish the test case.)

Is there a way I can mock the isAuthenticated variable to true and allow my test case to run without having to comment the authentication out? Can anyone help me authenticate my requests through mocha/chai?



via jch84

No comments:

Post a Comment