2015-05-19 93 views
1

我想在我的本地cassandra數據庫上運行一個簡單的測試,以檢查select語句是否從表中返回正確的記錄no。但是,放在前後塊之間的代碼沒有被調用。結果我的測試簡直失敗了。摩卡之前和之後掛鉤不執行

var assert = require('assert'); 
var cassandra = require('cassandra-driver'); 
var async = require('async'); 

//Connect to the cassandra cluster, assuming that the keyspace & columnspace already exists 
var client = new cassandra.Client({contactPoints: ['127.0.0.1'], keyspace: 'demo'}); 
describe('Cassandra is up and running', function() { 
    before(function() { 
     //Check if the connection got established successfuly 
     client.connect(function(err) { 
      if(err){ 
       console.log("Oops, something went wrong : " + err); 
      } 
      console.log('I al here 1'); 
     }); 

     //Insert a few data to column space 
     var queries = [ 
     { 
     query: 'INSERT INTO users(key, name, emails) VALUES (?, ?, ?)', 
     params: ['mick-jagger1', 'Sir Mick Jagger 1', '[email protected]'] 
     }, 
     { 
     query: 'INSERT INTO users(key, name, emails) VALUES (?, ?, ?)', 
     params: ['mick-jagger2', 'Sir Mick Jagger 2', '[email protected]'] 
     }, 
     { 
     query: 'INSERT INTO users(key, name, emails) VALUES (?, ?, ?)', 
     params: ['mick-jagger3', 'Sir Mick Jagger 3', '[email protected]'] 
     }, 
     { 
     query: 'INSERT INTO users(key, name, emails) VALUES (?, ?, ?)', 
     params: ['mick-jagger4', 'Sir Mick Jagger 4', '[email protected]'] 
     } 
     ]; 

     client.batch(queries, { prepare: true }, function(err) { 
      if(err){ 
       console.log("Oops, something went wrong : " + err); 
      } 
      console.log('Sample data inserted into column space'); 
     }); 
    }) 

    it('should return 4 when four rows of data are inserted into demo table', function() { 
     var count = 0; 
     client.execute('SELECT COUNT(*) FROM users', function(err, result) { 
      count = result.rows[0]; 
     }); 
     assert.equal(4, count); 
     console.log("I am here : " + count); 
    }) 

    after(function() { 
     client.execute('TRUNCATE users', function(err, result) { 
      if(err){ 
       console.log("Oops, something went wrong : " + err); 
      } 
     }); 
    }) 
}) 

回答

3

您的測試正在執行異步操作。當你的it/before/after函數完成時,你需要使用回調來告訴mocha。例如:

before(function(done) { 
    // ... 
    client.batch(queries, { 
     prepare: true 
    }, function(err) { 
      if (err) { 
       console.log("Oops, something went wrong : " + err); 
      } 
      console.log('Sample data inserted into column space'); 
      done(); 
     }); 
}); 

和:

it('should return 4 when four rows of data are inserted into demo table', function(done) { 
    var count = 0; 
    client.execute('SELECT COUNT(*) FROM users', function(err, result) { 
     count = result.rows[0]; 
     assert.equal(4, count); 
     console.log("I am here : " + count); 
     done(); 
    }); 
}); 
+0

值得一提的是,'client.batch'應該叫'client.connect'回調裏面,因爲'client.connect'是異步的了。或者,您可能最終會在完成連接之前執行查詢。 –

+0

謝謝你對回調的一些看法。現在我可以執行之前和之後的部分測試。 – BarryVenom