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.