Question

If I try to drop the database using after (at the end of my tests) it works.

If I try the following:

var db = mongoose.connect('mongodb://localhost/db-test')

describe('Database', function() {

    before(function (done) {
        db.connection.db.dropDatabase(function(){
            done()
        })
    })

    ...

it does not drop the DB. what is going on? I would prefer dropping the db before starting testing -- so that after testing I can explore the db.

Was it helpful?

Solution

solved by connect in another define.. not sure if ideal.

describe('Init', function() {

    before(function (done) {   
        mongoose.connect('mongodb://localhost/db-test', function(){
            mongoose.connection.db.dropDatabase(function(){
                done()
            })    
        })
    })

    describe('Database', function() {

OTHER TIPS

I implemented it a bit different.

  1. I removed all documents in the "before" hook - found it a lot faster than dropDatabase().
  2. I used Promise.all() to make sure all documents were removed before exiting the hook.

    beforeEach(function (done) {
    
        function clearDB() {
            var promises = [
                Model1.remove().exec(),
                Model2.remove().exec(),
                Model3.remove().exec()
            ];
    
            Promise.all(promises)
                .then(function () {
                    done();
                })
        }
    
        if (mongoose.connection.readyState === 0) {
            mongoose.connect(config.dbUrl, function (err) {
                if (err) {
                    throw err;
                }
                return clearDB();
            });
        } else {
            return clearDB();
        }
    });
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top