Using after to clean up in mocha, problems with mongo

259 views Asked by At

Ok, in the after function console.log "enter after function" and console.log "exit" executes, but console.log "WHYYYY" does not execute. I can't figure out why. For the record, console.log 'insert' does execute. I am making a similar call to mongo in one of my tests, so calling mongo should work.

Any clues to this problem or how to resolve it?

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

There are 1 answers

0
taminov On BEST ANSWER

Mongo doesn't have enough time to connect,

Try using the done callback in after function:

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