【问题标题】:asynchronous callback in mocha test摩卡测试中的异步回调
【发布时间】:2015-11-25 07:57:07
【问题描述】:

以下代码对我来说似乎不正确,可能可以用更好的方式编写。

对于异步测试,mocha需要调用回调,即:done();

这是我在 mocha 测试用例中的“之前”:

before(function (done) {
    get_open_db("./test/test.db")
    get_do_check_db(function() {
        done()
    })
})

在实际的代码段中,我为do_check_db添加了一个参数,即:cb(),以便done回调起作用。

function do_check_db(cb) {
        check_database(function(db_dates) {
            var most_recent_date = db_dates[0]["row.date_id"]
            var least_recent_date = db_dates[db_dates.length - 1]["row.date_id"]
            set_useful_dates(helpers.UsefulDates(most_recent_date, least_recent_date))
            console.log(get_useful_dates())
            if (most_recent_date != useful_dates.today_str ) {
                console.log(("Datebase not recent! Data being used is from: " + most_recent_date).red)
            } else {
                console.log("Database running with latest data!".green)
                most_recent_date = undefined
            }
            cb && cb()
        })
}

这似乎工作得很好,但是,有没有办法阻止向函数添加回调?我只添加了 cb 以使 mocha 正常工作。

【问题讨论】:

    标签: javascript node.js asynchronous callback mocha.js


    【解决方案1】:

    您的get_do_check_db 函数 是异步的,因此只有需要回调才有意义。 Mocha(或其他任何东西)怎么知道函数完成了?如果您不关心它实际上在之前运行您的第一个测试之前完成,只需在之后直接调用 done(或者根本不提供 done 参数)。

    before(function (done) {
        get_open_db("./test/test.db")
        get_do_check_db();
        done();
    })
    

    但我怀疑您希望get_do_check_db 在第一次测试运行之前完成,在这种情况下,您所拥有的非常合适。

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 2018-05-24
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 2017-07-29
      • 2018-02-03
      • 1970-01-01
      相关资源
      最近更新 更多