【问题标题】:How to use mongoose in mocha unit test?如何在 mocha 单元测试中使用猫鼬?
【发布时间】:2014-10-12 07:28:04
【问题描述】:

感觉很迷茫,怎么单元测试涉及到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

【问题讨论】:

标签: node.js mongodb mongoose mocha.js


【解决方案1】:

您正在同步运行测试。

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

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 来消除回调。
  • 你不能完全消除回调,你能做的最好的事情就是将它们展平,从而避免回调地狱。 async 使异步函数易于使用和相互结合。
猜你喜欢
  • 2019-05-04
  • 2018-12-30
  • 2017-09-30
  • 2016-05-19
  • 2017-10-11
  • 2019-03-24
  • 2015-07-08
  • 2017-02-27
  • 2017-08-11
相关资源
最近更新 更多