Best practice and most efficient way to setup a database connection for mocha tests

Viewed 1540

I have a set of tests which I run on my code. Before the tests run I would like to open a database connection to the testing database and make sure the db is empty. This connection will remain open for all the tests. Then, when all the tests have completed, close the database connection and empty the database.

My current solution involves opening a connection for each file, which will lead to a large amount of connections overall. It would be ideal to open the connection once --> run tests --> clear db --> close connection once.

Here is the code for one of my mocha test files:

import {assert} from 'chai';
import mongoose from 'mongoose';
import User from '../../../server/models/user.js';
import 'dotenv/config';

mongoose.connect(process.env.DB_TEST).then(db => {
  describe('User Model', function() {
    it('Save', function(done) {
      var john = new User({
        name: {
          first: 'John',
          last: 'smith'
        },
        email: 'john.smith@gmail.com',
        type: 'student'
      });

      john.save(done);
    });
  });
}).catch(err => {
  console.log('Failed to connect to testing database: ' + err);
});

Currently, this code is completely functional. However, I am sure there is a much better way to handle opening, clearing, and closing the database connection for my collection of tests.

1 Answers

You can use what I call Root level hooks.

Example :

Files of test

test0.es6
test1.es6
test2.es6
...

Use the test0.es6 file to handle the database connection, like :

// ROOT HOOK Executed before the test run
before((done) => {
  connectToDatabase()
    .then(() => {
       ...
       done();
    })
    .catch(...);
});

// ROOT HOOK Excuted after every tests finished
after((done) => {
  disconnectFromDatabase()
    .then(() => {
       ...
       done();
    })
    .catch(...);
});

Use the others files to perform your tests using the database connection :

/** @test {core} */
describe('core', () => {
  /** @test {core#executeCommandApi} */
  describe('executeCommandApi()', () => {
    it(...);
  });
});

Things to know: Mocha call your files in an alphabetical order

Related