Unit testing 使用mocha进行所有测试后,在何处删除数据库并关闭连接
我试图找出在所有测试运行后,在何处放置删除数据库和关闭连接的函数 以下是我的嵌套测试:Unit testing 使用mocha进行所有测试后,在何处删除数据库并关闭连接,unit-testing,node.js,mongoose,mocha.js,Unit Testing,Node.js,Mongoose,Mocha.js,我试图找出在所有测试运行后,在何处放置删除数据库和关闭连接的函数 以下是我的嵌套测试: //db.connection.db.dropDatabase(); //db.connection.close(); describe('User', function(){ beforeEach(function(done){ }); after(function(done){ }); describe('#save()', function(){
//db.connection.db.dropDatabase();
//db.connection.close();
describe('User', function(){
beforeEach(function(done){
});
after(function(done){
});
describe('#save()', function(){
beforeEach(function(done){
});
it('should have username property', function(done){
user.save(function(err, user){
done();
});
});
// now try a negative test
it('should not save if username is not present', function(done){
user.save(function(err, user){
done();
});
});
});
describe('#find()', function(){
beforeEach(function(done){
user.save(function(err, user){
done();
});
});
it('should find user by email', function(done){
User.findOne({email: fakeUser.email}, function(err, user){
done();
});
});
it('should find user by username', function(done){
User.findOne({username: fakeUser.username}, function(err, user){
done();
});
});
});
});
似乎什么都不管用。我得到错误:超过2000ms超时您可以在()之后定义一个“根”hook,在第一个descripe()
之前处理清理:
after(function (done) {
db.connection.db.dropDatabase(function () {
db.connection.close(function () {
done();
});
});
});
describe('User', ...);
不过,您得到的错误可能来自3个异步挂钩,它们没有通知Mocha继续。这些需要调用done()
或跳过参数,以便将它们视为同步:
describe('User', function(){
beforeEach(function(done){ // arg = asynchronous
done();
});
after(function(done){
done()
});
describe('#save()', function(){
beforeEach(function(){ // no arg = synchronous
});
// ...
});
});
:
通过将回调(通常称为done
)添加到it()
Mocha将知道它应该等待完成
我实现的有点不同
我删除了“before”钩子中的所有文档-发现它比dropDatabase()快得多
我使用Promise.all()确保在退出挂钩之前删除所有文档
beforeEach(function (done) {
function clearDB() {
var promises = [
Model1.remove().exec(),
Model2.remove().exec(),
Model3.remove().exec()
];
Promise.all(promises)
.then(function () {
done();
})
}
if (mongoose.connection.readyState === 0) {
mongoose.connect(config.dbUrl, function (err) {
if (err) {
throw err;
}
return clearDB();
});
} else {
return clearDB();
}
});
实际上,我在第二次运行make test时遇到了这个错误:`✖ 5个测试中有1个失败:1)每个“钩子”之前的用户#save():错误:超过2000ms的超时时间,在每个“钩子”之前的“@chovy It's's giving your direction--”“。因此,您在每个
之前都有一个尚未结束,可能是因为您已将参数命名为接受回调,但没有调用它。使用Mocha时,您必须将其保留为未命名(0个参数)——function(){…}
——或者将其命名并调用--function(done){done();}
。我现在遇到了一个不同的错误:1)“毕竟”钩子:错误:超时2000毫秒exceeded@chovy错误源似乎不在该文件中。不过,我运行了一个稍微修改过的版本:我必须将我的--timeout增加到4000,因为删除数据库显然要延迟一两秒钟。