我有多个带有单元测试的文件。我不想跟他们搭讪。我需要关闭猫鼬连接,以便gulp-jasmine到出口。我还想避免将连接处理放在it块中,因为它不属于那里。
如果我将连接/断开函数移动到beforeAll和afterAll。
代码
单元试验
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()然后Jasmine执行next describes beforeAll,然后afterAll才能正确断开数据库连接。
(茉莉花博士)撕下来]
但是,要小心使用beforeAll和afterAll!由于它们没有在规范之间重置,因此很容易意外地在您的规范之间泄漏状态,从而导致它们错误地通过或失败。
连接函数
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()编辑:
侦听断开事件也不起作用: exports.disconnectDB =(回调) -> console.log“断开DB",mongoose.connection.readyState mongoose.disconnect ( err )->返回回调错误(如果是错误的话?)连接-- console.log“应该是DISCONNETCED",mongoose.connection.readyState #并不是因为状态为3 0>断开了返回回调()
mongoose.connection‘断开连接’,() -> console.log "DIS",mongoose.connection.readyState返回回调()
错误
{ Error: Trying to open unclosed connection.
问题
如何正确打开和关闭与gulp-jasmine的连接
发布于 2016-09-23 08:49:11
这似乎很有效,但我仍然想知道为什么我不能使用disconnected事件:
connections = 0
disConnectionRetries = 0
MAX_DISCONNECTION_RETRIES = 10
connectDB = (callback) ->
console.log "CONNECTING TO DB", mongoose.connection.connectionState
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', () ->
connectionRetries = 0
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) ->
console.log "DISCONNECTING FROM DB", mongoose.connection.readyState
mongoose.disconnect (err)->
return callback err if err?
connections--
isDisconnected(callback)
isDisconnected = (callback)->
console.log "SHOULD BE DISCONNETCED", mongoose.connection.readyState
throw new Error "Cannot disconnect more than #{MAX_DISCONNECTION_RETRIES} retries" if disConnectionRetries > MAX_DISCONNECTION_RETRIES
if mongoose.connection.readyState == 0
disConnectionRetries = 0
return callback()
else
disConnectionRetries++
return setTimeout ()->
isDisconnected(callback)
, 50https://stackoverflow.com/questions/39655560
复制相似问题