gpt4 book ai didi

node.js - 在运行测试之前, Mocha 似乎不会等待 promise 链完成

转载 作者:行者123 更新时间:2023-12-03 22:21:05 24 4
gpt4 key购买 nike

我正在使用 Mocha 在我的代码中测试数据库交互(因此我无法模拟数据库)。
为了测试工作,我想在每次测试之前清理我的数据库。根据我的研究,我应该使用 Mocha 的能力来处理 before 函数返回的 promise 。
这是我试图实现这一目标的方法:

const Orm = require('../db');

describe('Loading Xml Files to Database should work', () => {
before(() => {
return Orm.models.File.destroy({force: true, truncate: true, cascade: true});
});

it('run test', () => {
loadXmlFileToDatabase(....); // this loads data from a
// file into the table "files"
Orm.Orm.query("SELECT * FROM files")
.then(function (result){
console.log(result);
})
.catch(function(error){
console.log(error);
});
});
});
但是,我在代码末尾从我的查询中返回零行。如果我省略 before() 函数,一切都会发生,所以我的结论是,由于某种原因,Mocha 没有等待它完成。
在我的测试运行之前,我如何确保 before() 函数完成?

最佳答案

Mocha 期望一个函数返回一个 promise 以等待它。
要么明确地 return 一个来自普通函数的 promise ,要么使用 asyncawait 函数

describe('Loading Xml Files to Database should work', function(){

before(async function(){
await Orm.models.File.destroy({force: true, truncate: true, cascade: true});
});

it('run test', async function(){
await loadXmlFileToDatabase(....); // this loads data from a
// file into the table "files"
const result = await Orm.Orm.query("SELECT * FROM files");
expect(result).to.eql({})
})

});

关于node.js - 在运行测试之前, Mocha 似乎不会等待 promise 链完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64260034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com