【问题标题】:Mocha is unable to find my dynamically generated tests?Mocha 找不到我动态生成的测试?
【发布时间】:2019-01-31 06:00:51
【问题描述】:

使用 for 循环生成测试时,会在框架中检测到动态测试。但是对于一个特定的套件,我需要从数据库中获取数据并基于它创建测试。我正在使用的程序如下

 describe("Testing existence of elements", function (existence_suite_done) {

    let elements = [];
    models.cypher('match (a:page {id: "74ab8f9d-e24b-41d1-9390-d6fb338ece38"})-[r:child]->(b:element) return b;')
      .then((data) => {
        elements = data.records;
      })
      .then(() => {
        for(var i=0;i<elements.length;i++) {
          it('hello', (done) => {
            done();
          });
        }
      })
      .then(existence_suite_done)
      .catch(existence_suite_done);
  });

现在我很好奇,当测试依赖于 Promise 的结果时,如何让该套件专门工作。我想它与范围有关,但无法弄清楚我哪里出错了。任何帮助表示赞赏

【问题讨论】:

  • 尝试将获取数据放入it(...)
  • @Sergey 没用

标签: javascript node.js mocha.js


【解决方案1】:

这应该可行。

// Your async data fetching emulation.
var models = {
    cypher: () => {
        return new Promise((resolve, reject) => {
            setTimeout(function () {
                resolve({ records: ['A', 'B', 'C', 'D', 'E'] });
            }, 300);
        });
    }
};


// The data query is inverted with respect to the loop.
describe("Testing existence of elements", function () {
    let elements;

    it('Fething and testing data', () => {
        return models.cypher()
            .then((data) => {
                elements = data.records;
            })
            .then(() => {
                for (var i = 0; i < elements.length; i++) {
                    var el = elements[i];
                    console.log(`Testing ${el} ...`);
                }
            });
    });
});

或者,您可以返回Promise (docs),而不是使用done() callback

附言

似乎 Mocha 确实只在 describe 的套件函数中寻找测试。因此,它不会等待您的数据获取异步回调来查看它。

在这里我找到了a similar question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多