[英]How can I avoid my Q promise catch block being called twice in a NodeJS callback-style API when running mocha unit tests?
[英]callback being called twice when my unit test fails
我無法弄清楚為什么在回調失敗時我的mocha測試中會調用兩次保存回調。 它不會調用保存兩次,它只會再次觸發保存的回調,但是當我的第二個單元測試失敗時會出現'should'錯誤。 如果我取出失敗的'should'斷言應該。從第二次測試中出現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", "quark@ds9.com", "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", "quark@ds9.com", "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)
嗯,首先,測試具有預定義的順序是不好的形式。 您的第二個測試應該嘗試將兩個用戶保存到數據庫,而不是依賴於第一個測試。
其次,我只能假設db
在這個上下文中是一個node-neo4j Database
,你的斷言框架(should.js?chai?)正在使用異常。 所以我的答案是基於這個假設。
似乎node-neo4j在異常情況下正在調用回調函數。
試着throw 'blah'
而不是should
斷言,看看你是否可以縮小它。 這沒有在node-neo4j文檔中列出,所以它看起來像一個bug。
請參閱: http : //coffeedoc.info/github/thingdom/node-neo4j/master/classes/Node.html#save-instance
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.