const mocha = require('mocha');
const assert = require('assert');
const MarioChar = require('../models/mariochar');
describe('Some demo tests', function(){
//Create tests
it('Saves a record to the database', function(done){
var character = new MarioChar({
name: "Mario",
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
})
})
character.save().then(function(){
assert(character.isNew === false)
done();
})
The above function saves the character in the database.
character.isNew returns true when the object is created but not present in the database.
and returns false when the object is found in the database.
As save is an asynchronous function, to perform next tests we have to explicitly tell when it is finished through done method.
2. Using ES6 promise instead using mogoose's own promise
const mongoose = require('mongoose');
// Using ES6 promise instead mogoose's promise
mongoose.Promise = global.Promise
// Connect to mongodb
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
...
}).on('error', function(error){
...
})
At this point our test is being ran even before the connection is established.
To do that we have to put our connection code inside before
before(function(done){
mongoose.connect('mongodb://localhost/testaroo');
mongoose.connection.once('open', function(){
console.log('Conneciton is made');
done();
}).on('error', function(error){
console.log('Connection error', error);
})
})
Note that we've also used done to explicitly tell when the connection is established.
Top comments (0)