2012-12-16 41 views
12

我想弄清楚在所有測試運行後刪除數據庫和關閉連接的功能。在哪裏刪除數據庫並關閉所有使用摩卡測試之後的連接

這裏是我的嵌套的測試:

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

似乎沒有任何工作。我得到錯誤:2000毫秒的超時超過

回答

20

可以定義一個「根」之前一日describe()after()鉤來處理清理:

after(function (done) { 
    db.connection.db.dropDatabase(function() { 
     db.connection.close(function() { 
      done(); 
     }); 
    }); 
}); 

describe('User', ...); 

雖然,你得到可能是從3個異步錯誤掛鉤不通知摩卡繼續。這些都需要或者調用done()或跳過的說法,使他們能夠爲同步處理:

describe('User', function(){ 
    beforeEach(function(done){ // arg = asynchronous 
     done(); 
    }); 

    after(function(done){ 
     done() 
    }); 

    describe('#save()', function(){ 
     beforeEach(function(){ // no arg = synchronous 
     }); 

     // ... 
    }); 
}); 

From the docs

By adding a callback (usually named done) to it() Mocha will know that it should wait for completion.

+0

其實,我得到這個錯誤的第二次運行make test:'✖1 5的測試失敗: 1)用戶#save()勾 「每個前」: 錯誤:超時超過2000毫秒' – chovy

+0

@chovy在每個「hook *」之前它給了你方向 - '*'。因此,你有一個'beforeEach'沒有完成,可能是因爲你已經命名了接受回調的參數,但是然後不調用它,用Mocha,你必須保留它未命名(0個參數) - function(){...} - 或命名並調用它 - function(done){done ();}'。 –

+0

我現在得到了一個不同的錯誤:https://gist.github.com/a821 7751061ad6e738b9 1)「畢竟」掛鉤: 錯誤:超過2000毫秒超時 – chovy

0

我實現它有點不同。

  1. 我刪除了「before」鉤子中的所有文檔 - 發現它比dropDatabase()快得多。
  2. 我使用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(); 
        } 
    }); 
    
相關問題