3

I feel very confused, how to unit test involves mongodb in mocha, I still can not successfully call the save function with no exception is thrown.

I try to use the most simple example for testing and found that 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 created in the mongodb .

> show collections
pieces
sequences
system.indexes
Leonid Beschastny
  • 43,908
  • 9
  • 107
  • 112
elrrrrrrr
  • 796
  • 6
  • 15
  • Check this one it could be the answer to your question :) http://stackoverflow.com/questions/13320564/how-do-i-use-should-with-mocha-and-mongoose – Roy Mourad Aug 19 '14 at 09:03

1 Answers1

6

You're running your test synchronously.

To execute async test you should add 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);
})
Leonid Beschastny
  • 43,908
  • 9
  • 107
  • 112
  • It works,I am trying to use **async** to eliminate the callbacks. – elrrrrrrr Aug 19 '14 at 15:46
  • You can't eliminate callback completely, the best thing you can do is to flatten them, thus escaping callbacks hell. `async` makes asynchronous functions easy to use and combine with each other. – Leonid Beschastny Aug 19 '14 at 15:58