I have a problem with the mongoose.createConnection function , here is my code for the tests:
"use strict";
let mongoose = require('mongoose'),
expect = require('chai').expect,
dbURI = 'mongodb://localhost/node_marque_test',
Marque = require('../lib/marque.js');
before(function(done){
let connection = mongoose.createConnection(dbURI);
connection.on('open', function(){
Marque.remove(function(err, marques){
if(err){
console.log(err);
throw(err);
} else {
done();
}
})
})
})
afterEach(function(done){
Marque.remove().exec(done);
})
describe('an instance of Marque', ()=>{
let marque;
beforeEach((done)=>{
marque = new Marque({name: 'YAMAHA'})
marque.save((err)=>{
if(err){throw(err);}
done();
})
})
it('has a nom', ()=>{
expect(marque.name).to.eql('YAMAHA');
})
it('has a _id attribute', ()=>{
expect(marque).to.have.property('_id')
})
})
And here is the Mark object code :
"use strict";
let mongoose = require('mongoose'), Schema = mongoose.Schema;
let marqueSchema = Schema({
name: { type: String, required: true}
});
let Marque = mongoose.model('Marque', marqueSchema);
Marque.schema.path('name').validate(name_is_unique, "This name is already taken");
function name_is_unique(name,callback) {
Marque.find({$and: [{name: name},{_id: {$ne: this._id}}]}, function(err, names){
callback(err || names.length === 0);
});
}
module.exports = mongoose.model('Marque');
So when I run npm test , I got this error:
1) "before all" hook
0 passing (2s)
1 failing
1) "before all" hook:
Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
But if I replaced
let connection = mongoose.createConnection(dbURI);
connection.on('open', function(){
Across
mongoose.connect(dbURI);
mongoose.connection.on('open', function(){
Everything works and passes the test:
an instance of Marque
β has a nom
β has a _id attribute
2 passing (65ms)
The problem is that I need to do tests with multiple values, so I cannot use mongoose.connect (otherwise I received Error: attempt to open a closed connection. )
So how can I use createConnection to connect to mongoose inside my tests?
Thank you for your help:)