如何在mocha单元测试中使用mongoose?

3

我感到非常困惑,如何在mocha中进行涉及mongodb的单元测试,我仍然无法成功调用save函数而不抛出异常。

我尝试使用最简单的示例进行测试,并发现仍然存在问题。以下是我的代码。

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');
      });

    })
  })
})

这段代码并不会抛出异常,但是在mongodb中没有数据被更新或创建。

> show collections
pieces
sequences
system.indexes

看看这个,它可能是你问题的答案 :)https://dev59.com/-GrXa4cB1Zd3GeqPBq-s - Roy Mourad
1个回答

6

您正在同步运行测试。

要执行异步测试,您需要添加回调函数:

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();
    }
  });
})

或者简单地说
it('should has increment', function(done){
  var Cat = mongoose.model('Cat', { name: String });
  var kitty = new Cat({ name: 'Zildjian' });
  kitty.save(done);
})

它可以工作,我正在尝试使用async来消除回调。 - elrrrrrrr
你无法完全消除回调,最好的方法是将它们扁平化,从而避免回调地狱。async使异步函数易于使用和组合。 - Leonid Beschastny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接