使用 Vows 和 Mongoose 进行异步测试
使用 Vows/Coffeescript/Mongoose 并遇到数据库异步问题。
在运行测试之前,我会进行一系列设置,包括清除测试数据库。一旦我对最后一个文档调用了删除,我就会触发回调,以便 Vows 可以继续测试的下一步。问题在于,无法保证数据库实际上已被清除,因为事情是异步发生的。在这种情况下,我实际上想要同步,但我不确定如何实现这一点。
这是代码(Vows 片段,然后是清除函数 def):
'AND the test database is empty':
topic: ->
testDB.purge "widgets_test", @callback
purge = (database, callback) ->
db = mongoose.connect "mongodb://localhost/#{database}"
modelCount = Models.length
for model in Models
modelCount--
model.find {}, (err, docs) ->
docCount = docs.length
for doc in docs
doc.remove (err) ->
docCount--
# do callback after all data has been purged - setTimeout HACKHACKHACK
if modelCount is 0 and docCount is 0
setTimeout ->
callback()
, 100
执行此操作的正确方法是什么?
Using Vows/Coffeescript/Mongoose and running into an async issue with DB.
Before my tests run I do a bunch of set up, including purging the test database. Once I have called remove on the last doc, I fire off the callback so Vows can carry on to the next step in the test. The trouble is that there's no guarantee the DB will actually have been purged since things happen async. In this case I actually WANT sync but I'm not sure how to make that happen.
Here's the code (Vows snippet and then the purge function def):
'AND the test database is empty':
topic: ->
testDB.purge "widgets_test", @callback
purge = (database, callback) ->
db = mongoose.connect "mongodb://localhost/#{database}"
modelCount = Models.length
for model in Models
modelCount--
model.find {}, (err, docs) ->
docCount = docs.length
for doc in docs
doc.remove (err) ->
docCount--
# do callback after all data has been purged - setTimeout HACKHACKHACK
if modelCount is 0 and docCount is 0
setTimeout ->
callback()
, 100
What's the right way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我使用的技巧是在单独的批次中进行此设置/拆卸,然后再在后续批次中运行测试。
它似乎对我有用(我还使用誓言和 Mongo)
The trick I use is to do this setups/teardowns in separate Batchs before you run your tests in a subsequent Batch.
It seems to work for me (I'm using also vows and Mongo)