简体   繁体   English

Mocha无法找到我动态生成的测试?

[英]Mocha is unable to find my dynamically generated tests?

While generating the tests using a for loop the dynamic tests are detected in the framework. 使用for循环生成测试时,将在框架中检测动态测试。 But for one specific suite I need to fetch data from database and create tests based on that. 但是对于一个特定的套件,我需要从数据库中获取数据并基于该套件创建测试。 The program that I am using is as follows 我正在使用的程序如下

 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);
  });

Now I am curious how to get that suite working specifically when the tests are dependent on results from a promise. 现在我很好奇,当测试依赖于承诺的结果时,如何使该套件特别起作用。 I imagine it has something to do with scopes but am unable to figure out where I am going wrong. 我想它与范围有关,但无法弄清楚我要去哪里。 Any help is appreciated 任何帮助表示赞赏

This should work. 这应该工作。

// 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} ...`);
                }
            });
    });
});

Alternately, instead of using the done() callback , you may return a Promise ( docs ). 或者,您可以返回Promisedocs ),而不是使用done() callback

PS PS

It seems that Mocha does look for tests only within the describe's suite function. 看起来Mocha确实只在describe的套件功能内寻找测试。 So, it won't be waiting for your data fetching async callback to look into it. 因此,它不会等待您的数据获取异步回调对其进行调查。

Here I found a similar question . 在这里,我发现了一个类似的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM