I have multiple files with unit tests. I want to avoid to concat them. I need to close the mongoose connection in order for gulp-jasmine
to exit. I also want to avoid to put the connection handling into an it
block, because it wouldn't belong there.
If I move my connect/disconnect function into beforeAll
and afterAll
e.g.
Code
Unit Tests
describe "a unit test"
beforeAll (done)->
db = testSettings.connectDB (err)->
throw err if err?
done()
...
afterAll (done)->
testSettings.disconnectDB (err)->
throw err if err?
done()
Then Jasmine executes the next describes beforeAll
before afterAll
could disconnect the db properly.
(Jasmine Docs)[http://jasmine.github.io/2.1/introduction.html#section-Setup_and_Teardown]
However, be careful using beforeAll and afterAll! Since they are not reset between specs, it is easy to accidentally leak state between your specs so that they erroneously pass or fail.
Connection Function
connections = 0
exports.connectDB = (callback) ->
configDB = require(applicationDir + 'backend/config/database.js')(environment)
if connections == 0
mongoose.connect configDB.url,{auth:{authdb:configDB.authdb}}, (err)->
if (err)
console.log(err)
return callback err
db = mongoose.connection
db.on 'error', console.error.bind(console, 'connection error:')
db.once 'open', () ->
connections++
return callback null, db
#console.log "Database established"
#Delete all data and seed new data
else
db = mongoose.connection
return callback null, db
exports.disconnectDB = (callback) ->
mongoose.disconnect (err)->
return callback err if err?
connections--
return callback()
EDIT:
Listening for disconnect event does not work either: exports.disconnectDB = (callback) -> console.log "DISCONNECTING FROM DB", mongoose.connection.readyState mongoose.disconnect (err)-> return callback err if err? connections-- console.log "SHOULD BE DISCONNETCED", mongoose.connection.readyState #is not because state is 3 0> disconnecting return callback()
mongoose.connection 'disconnected', () -> console.log "DIS", mongoose.connection.readyState return callback()
Error
{ Error: Trying to open unclosed connection.
Question
How to properly open & close my connections with gulp-jasmine
?
This seems to work, still wondering why I can't use the
disconnected
event: