【问题标题】:db.close() promise pending : Jest did not exit one second after the test run has completeddb.close() promise pending : 测试运行完成后一秒 Jest 没有退出
【发布时间】:2020-08-25 23:52:51
【问题描述】:

尝试学习玩笑,使用下面的代码测试不会终止。 db.close promise 的状态仍然是pending。

我在执行测试时收到以下消息。你能帮我解决这个问题吗?谢谢。

Jest 在测试运行完成后一秒没有退出。

这通常意味着在您的测试中存在未停止的异步操作。考虑使用 --detectOpenHandles 运行 Jest 来解决此问题。

test('Should be ', async () => {

    /*DO NOT call the next four function directly,  check if a  merchant/terminal exists before starting
    a transaction and insert document if required.*/
    //functions.insertTerminalRecordInMongo();
    //functions.insertTerminalRecordInMongo();

    var record = await functions.getMongoField('terminal', {'attributes.TID': 'T55001001'});
    //functions.deleteTerminalRecordInMongo('terminal',{'attributes.TID' :'T55001001'})
    DE22Test.buildTransactionAndSend({MTI: "1104", dataElements: {DE22: "XYZ"}})
    expect(functions.getAsRequestField('DE22')).toBe("XYZ")
    expect(functions.getAsResponseField('DE39')).toBe("00")
    expect(functions.getAsResponseField('DE01')).toBe("00")
})

从 mongodb 中检索文档的函数。

 //Return a mongo record based on collectionName and FieldName
    getMongoField: (collectionName, queryElement) => {
        console.info("Querying Mongo");
        mongoClient.connect(uri, function (err, db) {
            if (err) throw err;
            dbo = db.db("axis")
            dbo.collection(collectionName).find({}, queryElement).toArray(function (err, result) {
                if (err) throw err;
                console.info('Queried document', result[0]);
            });
            db.close()
        })
    },

【问题讨论】:

    标签: javascript mongodb jestjs


    【解决方案1】:

    对不起,我想发表评论,但由于声誉较低,我不能发表评论。 从代码 sn-p 来看,数据库操作本质上是异步的,这意味着您需要实现异步代码,因此最后代码将在数据库关闭后终止。

    const db = await mongoClient.connect(uri)
    // Do your tasks
    await db.close()
    

    编辑

    不要忘记将代码包裹在 try catch 块中以进行错误处理。

    【讨论】:

    • 谢谢,我在单独的 javascript 中声明了 getMongoField 函数,如何实现异步?谢谢,普拉山
    • 哦,为了从那个文件中导出函数,并作为`await function_name()`运行,确保你将在其中运行这个函数的父函数必须是异步的。
    • 我建议你查看关于 async-await 和 promises 的材料。
    猜你喜欢
    • 2019-06-15
    • 2018-12-08
    • 2019-02-05
    • 2021-03-01
    • 2021-03-28
    • 1970-01-01
    • 2021-12-26
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多