Unit testing Mongoose models in separate files causes issues (using Mockgoose & Lab) Unit testing Mongoose models in separate files causes issues (using Mockgoose & Lab) mongoose mongoose

Unit testing Mongoose models in separate files causes issues (using Mockgoose & Lab)


I think the code you placed into each model is a hack. During the normal execution, require has "global" effect - once you import the module, it will not be imported second time.

Probably this normal flow is changed during the tests, but that means that it is better to find a solution which can be locally implemented inside the tests.

It also looks like you have the problem similar to what is discussed in this issue - OverwriteModelError with mocha 'watch'.

There are some solutions to try:

1) Create new mongoose connection each time:

var db = mongoose.createConnection()

2) Run the mocha via nodemon. This one looks puzzling for me, but still worth trying, maybe it makes each test to run completely independently. I also assume you use mocha for tests:

nodemon --exec "mocha -R min" test

3) Clear mongoose models and schemes after each test:

after(function(done){  mongoose.models = {};  mongoose.modelSchemas = {};  mongoose.connection.close();  done();});