使用 Vows 和 Mongoose 进行异步测试

发布于 2024-12-01 03:59:06 字数 866 浏览 1 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

兔姬 2024-12-08 03:59:06

我使用的技巧是在单独的批次中进行此设置/拆卸,然后再在后续批次中运行测试。

它似乎对我有用(我还使用誓言和 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文