【发布时间】:2021-01-23 08:29:41
【问题描述】:
我正在使用 Mocha 在我的代码中测试数据库交互(因此我无法模拟数据库)。 为了使测试正常工作,我想在每次测试之前清理我的数据库。根据我的研究,我应该使用 Mocha 的能力来处理由 before 函数返回的承诺。
这是我尝试实现的方法:
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() 函数在我的测试运行之前完成?
【问题讨论】:
-
应该可以。但是,您的
it测试本身不会等待它创建的承诺。 -
你找到我了,Bergi,“它”在哪里创造了一个承诺?
-
来自
Orm.Orm.query()的promise需要返回mocha等待。 -
可能还需要等待
loadXmlFileToDatabase()。 -
@MischaObrecht
Orm.query确实创建并返回了一个承诺(您与then和catch一起使用)
标签: node.js asynchronous promise sequelize.js mocha.js