单元测试失败时调用两次回调

时间:2012-08-31 15:57:53

标签: javascript unit-testing coffeescript mocha should.js

我无法弄清楚为什么在回调失败时我的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)

1 个答案:

答案 0 :(得分:1)

嗯,首先,测试具有预定义的顺序是不好的形式。您的第二个测试应该尝试将两个用户保存到数据库,而不是依赖第一个测试。

其次,我只能假设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