How to use mongoose in a mocha unit test?
I am very confused how the unit test includes mongodb in mocha, I still cannot successfully call the save function without exception.
I am trying to use the simplest example for testing and found there are still problems. Here is my code.
var assert = require("assert")
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/dev', function(err){
if(err) throw err
});
describe('increment Id', function(){
describe('increment', function(){
it('should has increment', function(){
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) throw err
console.log('meow');
});
})
})
})
This code does not throw an exception, but there is no data updated or generated in mongodb.
> show collections
pieces
sequences
system.indexes
+3
source to share
1 answer
You run your test in sync.
To perform an asynchronous test, you must add a callback function:
it('should has increment', function(done){
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(function (err) {
if (err) {
done(err);
} else {
console.log('meow');
done();
}
});
})
or simply
it('should has increment', function(done){
var Cat = mongoose.model('Cat', { name: String });
var kitty = new Cat({ name: 'Zildjian' });
kitty.save(done);
})
+6
source to share