我感到很困惑,如何在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);
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句