سؤال

I created a simple Restify server, and started testing its functionality through Mocha using its own JSONclient.

When Unit Testing functionality, it's possible to set an ENV var indicating a testing setup, and connect to the according mongodb database.

However, when using the JSONClient you, obviously, test the 'running' API server, which is already connected.

Is there any way to end-to-end test API functionality through the client by swithing database-connections as to not overwrite the development database?

Edit: I suppose I could add a method to the api along the lines of "switchDataConnection" which would switch to the testing database, but that feels dirty and hacky.

هل كانت مفيدة؟

المحلول

An approach that worked for me was an env.js file and a config.js file.

In config.js (really copied from config-dev.js and config-prod.js) I put all my configuration settings. Things like directory path information and database settings.

For example, this is my dev DB connection (I'm using the knexjs package):

var knex = {
  client : 'mysql',
  connection : {
    host : '127.0.0.1',
    user : 'root',
    password : 'pass',
    database : 'testdev',
    charset : 'utf8'
  }
};

In my production config, I simply have a different connection defined.

Then, in env.js, I required the config.js file to load the appropriate settings. In my unit tests, I can load the env.js for dev, and in app.js I can load for production.

Make sense? You are on the right path though, it is possible to have the same code testing against two different DBs.

EDIT from comments: I would suggest setting up a test environment where you can start your own API server on a different port, and then run your tests off that (which of course would connect to a test DB).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top