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