The reason for the failure seems that the event subscription in mongoose.connection.on('open',...)
remains bound to the callback from test1 even after disconnect and connect for test2. The extra call to the previous callback is the one causing trouble.
You should make sure to remove the subscription somehow when you are done with it. Since mongoose connection is based on nodejs EventEmitter then a simple solution might be to replace the call
mongoose.connection.on('open'...)
with
mongoose.connection.once('open'...)
but you could also use the general add/removeListener() as needed.
On a different note, it seems unneeded to connect and disconnect in each test of a unit test. You could just connect once by something like requiring a module that connects to your test database as in require('db_connect_test')
, the module db_connect_test should just call mongoose.connect(...)
and all the tests would run with the same connection (or pool as mongoose creates).
Have a good one!