Automated Testing with Databases Automated Testing with Databases postgresql postgresql

Automated Testing with Databases


In my app I use a config module to control configuration settings for different environments. When running tests the process.env.APP_ENV is set to test, and it will set the dialect to sqlite. Note that you will not have any data or data persistence, so you will need to populate it with all the data needed for your tests.

Include sqlite3

yarn add -D sqlite3

or

npm i -D sqlite3

Config

module.exports = {  database: {    name: 'dbname',    user: 'user',    password: 'password',    host: 'host',    // Use "sqlite" for "test", the connection settings above are ignored    dialect: process.env.APP_ENV === 'test' ? 'sqlite' : 'mysql',  },};

Database/Sequelize

// get our configconst config = require('../config');... // codeconst instance = new Sequelize(    config.database.name,    config.database.user,    config.database.password,    {      host: config.database.host,      // set the dialect, will be "sqlite" for "test"      dialect: config.database.dialect,    });

Test Class (Mocha)

const TestUtils = require('./lib/test-utils');describe('Some Tests', () => {  let app = null;  // run before the tests start  before((done) => {    // Mock up our services    TestUtils.mock();    // these are instantiated after the mocking    app = require('../server');    // Populate redis data    TestUtils.populateRedis(() => {      // Populate db data      TestUtils.syncAndPopulateDatabase('test-data', () => {        done();      });    });  });  // run code after tests have completed  after(() => {    TestUtils.unMock();  });  describe('/my/route', () => {    it('should do something', (done) => {      return done();    });  });});

Run Tests

APP_ENV=test ./node_modules/.bin/mocha

You could use ENV variables in other ways to set the dialect and connection parameters as well - the above is just an example based on what we have done with a lot of supporting code.