【问题标题】:Mocha does not seem wait for promise chain to complete before running testMocha 在运行测试之前似乎没有等待承诺链完成
【发布时间】: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 确实创建并返回了一个承诺(您与 thencatch 一起使用)

标签: node.js asynchronous promise sequelize.js mocha.js


【解决方案1】:

Mocha 期望函数返回一个等待它的承诺。 要么明确地 return 来自普通函数的承诺,要么使用 async 函数 await

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({})
  })

});

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2019-11-03
    • 2021-10-03
    • 2018-08-15
    • 2016-08-07
    • 2014-10-21
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    相关资源
    最近更新 更多