2012-08-31 51 views
4

我無法弄清楚爲什麼我的保存回調在回調失敗時在我的摩卡測試中被調用兩次。它不會調用保存兩次,它只會觸發保存的回調,但在第二次單元測試失敗時會出現「應該」錯誤。如果我從第二次測試中拿出失敗的「應該」斷言should.exist err它似乎工作正常,並且不會觸發保存索引回調兩次。當我的單元測試失敗時,回調被調用兩次

class User 

    constructor : (@name, @email, @pwd) -> 
    save : (callback) -> 
    unless this.validate() 
     throw new Error('invalid data') 
    else 
     user = 
     name : @name 
     email : @email 
     pwd : @pwd 

     node = db.createNode user 

     node.save (err) -> 
     unless err   
      user.id = node.id; 
      node.index 'User', 'name', user.name.toLowerCase(), (err2) -> 
      #why is this being fired twice when an assert in the callback fail? 
      console.log '----------- triggering the save callback' 
      callback err2, user 

     else 
      callback err 

摩卡測試

describe "User", -> 
    it "should be able to save", (done) -> 
     user = new User("quark", "[email protected]", "profit") 
     user.save (err, result) -> 
      should.exist result 
      done err 

    #this second unit test should fail since the duplicate checking is not yet implemented 
    it "should not allow duplicates to be saved", (done) -> 
     user = new User("quark", "[email protected]", "profit") 
     user.save (err, result) -> 
      console.log err 
      should.exist err #this triggers the user.save callback to be fired twice 
      done null 

,測試結果

User 
    ◦ should be able to save: ----------- triggering the save callback 
    ✓ should be able to save (43ms) 
    ◦ should not allow duplicates to be saved: ----------- triggering the save callback 
undefined 
----------- triggering the save callback 
{ name: 'AssertionError', 
    message: 'expected undefined to exist', 
    actual: undefined, 
    expected: undefined, 
    operator: undefined } 
    ✓ should not allow duplicates to be saved 


    ✔ 2 tests complete (69ms) 

回答

0

嗯,首先,具有有一個預定義的順序測試是拙劣的形式。您的第二次測試應該嘗試將兩個用戶保存到數據庫,而不是依賴於第一次測試。

其次,我只能假設db在這個上下文中是node-neo4j Database,並且您的斷言框架(should.js?chai?)使用異常。所以我的回答是基於這個假設。

看來node-neo4j正在調用異常情況下的回調函數。

試試只是做一個throw 'blah'而不是should斷言,看看你是否可以縮小到這一點。這在node-neo4j文檔中沒有列出,所以它看起來像一個錯誤。

參見:http://coffeedoc.info/github/thingdom/node-neo4j/master/classes/Node.html#save-instance

+0

是的,它是thingdom /節點的Neo4j和should.js – MonkeyBonkey