node.js - 如何在 Mocha 单元测试中使用 Mongoose ?

标签 node.js mongodb mongoose mocha.js

感觉很迷茫,怎么在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

最佳答案

您正在同步运行测试。

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

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

关于node.js - 如何在 Mocha 单元测试中使用 Mongoose ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25379309/

相关文章:

javascript - Mongo $facet 获取并统计聚合管道中匹配产品的标签

node.js - 按子子文档过滤子文档

python - 如何检查 mongo ObjectID 在 python 中是否有效?

javascript - Azure DocumentDB 中的 Mongoose $ne

javascript - 如何在 Mongoose 中分页而不重复?

javascript - 类型错误 : Cannot read property 'findAll' of undefined

c# - FileReader 不是用 Angular 服务器端渲染定义的

javascript - 从 JavaScript 字符串中提取嵌套的内联 Jade 元素

c# - mongodb c# 驱动程序 - 继承、映射和序列化问题

node.js - MongooseJS - 如何保存文档和引用的文档