使用after来清理mocha,mongo的问题

时间:2015-06-08 16:04:48

标签: node.js mongodb coffeescript mocha

好的,在after函数console.log "enter after function"console.log "exit"中执行,但console.log "WHYYYY"不执行。我无法弄清楚为什么。为了记录,console.log 'insert'确实执行。我在我的一个测试中对mongo进行了类似的调用,所以调用mongo应该可行。

此问题的任何线索或如何解决?

describe 'HTTP Requests', ->
    describe 'Socky', ->
        socky = new Socky config
        socky.listen()

        before ->
            mongo.open (error, db) =>
                secondDb = db.db config.api.accountTest
                secondDb.collection 'accounts', (error, accountsColl) =>
                    accountsColl.insert {'_id': ObjectID("#{ accountId }"), 'name': "test-account"}, (error, records) =>
                        console.log 'insert'
                        db.close()
                        return

                db.collection 'tokens', (error, tokensColl) =>
                    tokensColl.insert {'accountId': "#{ accountId }", 'userId': "#{ userId }", 'token': 'testtoken'}, (error, records) =>
                        null
                        db.close()
                    return
                db.close()
                return

        after ->
            console.log "enter after function"

            # console.dir mongo
            mongo.open (error, db) =>
                console.log "WHYYYY"
                secondDb = db.db config.api.accountTest
                console.log error


                secondDb.collection 'accounts', (error, accountsColl) =>
                    accountsColl.remove {}, (error, records) =>
                        console.log "remove?"
                        null
                        return

                db.collection 'tokens', (error, tokensColl) =>
                    tokensColl.remove {}, (error, records) =>
                        # db.close()
                        return
                return
            console.log "exit after"

1 个答案:

答案 0 :(得分:1)

Mongo没有足够的时间连接,

尝试在after函数中使用完成回调:

after (done) ->
  console.log "WHYYYY"
  mongo.open (error, db) =>
     ...
     done()
  console.log "exit after"
})