User different database connection parameters


#1

I would like to user a different database for running tests than when normally using hyperdev… I am using mongoose… and I connect in server.js using credentials saved in the environment variables… could anyone suggest how I might get my REST endpoints to use a different database when I am doing unit tests.
I saw a project online using mocha where they started up node.js using different scripts… one for testing and one for development… which meant that they could have different environment variables… but I dont think this can


#2

You only have one node server, so you can’t do it with environment variables as you would locally. I guess you could add an optional parameter to your routes that would tell them you’re testing and make them use a different DB connection. You might write an express middleware function that would check for that parameter, and set the right db connection on the request object, and then your routes could use that. Something like this:

app.use(
  function(req, res, next) {
    if (req.query.testing) {
      req.db = debugDbConn;
    }
    else {
      req.db = readDbConn;
    }

    next();
  }
);