【问题标题】:Running mocha tests synchronously同步运行 mocha 测试
【发布时间】:2025-12-08 18:05:02
【问题描述】:

我有以下设置来运行“it”测试:

X is environment variable
if( X == "all" || X == "some value" )
   read directory and run test using it() with callbacks

if( X == "all" || X  == "some other value")
   read directory and run some it() tests with callback

我面临的问题是,当我给出“某个值”或“某个其他值”时,所有的 it() 测试都运行得很好。但是当环境变量为“all”时,在运行第一个 it() 测试时,会出现第二个 if 语句的目录内容。我正在使用 fs.readdirSync(dir) 来读取内容,并且我知道 mochatest 异步运行它们,因此,第二个目录的内容出现在第一个测试中。是否可以阻止第二个 if 语句的执行,直到第一个 if 中的所有 it() 测试成功完成?或使其同步运行的任何替代方法。

【问题讨论】:

    标签: node.js mocha.js


    【解决方案1】:

    在 Mocha 中,it() 测试可以阻止,直到您说它完成。只需将“完成”回调传递给测试函数,如下所示:

    it( "running test", function( done ) {
      //do stuff, even async
      otherMethod( function(err, result ){
        //check err and result
        done();
      } );
    } );
    

    Mocha 也将在 describe() 块内连续运行 it() 测试。

    【讨论】:

    • 我确实有一个 done 回调,但问题是有多个 if 语句,并且其中有几个 it() 块。每个 if 都基于某个 env 变量读取一个目录,因此由于 mocha 异步运行并且当 env 变量为“all”时,它会继续读取每个 if 中的目录,覆盖第一个 if() 语句的内容,因此,测试失败...
    • if 块之外使用不同的变量,这样它们就不会被覆盖。 (不过,没有代码很难看到)。此外,在运行 Mocha 时,有 --grep 选项,您可以标记 describe 块以匹配模式。
    • 对每个 if 块使用不同的变量名确实解决了@clay 的问题。但是,不确定是否有更好的替代方案。
    • 嗯,这只是一个测试环境。无需变得复杂 :) 如果您愿意,您也可以在 if 块的末尾清空变量以重用相同的变量。如果一个测试填充了一个变量,并且下一个测试使用/更改该变量然后失败它的测试条件。 . .这只是测试设置的问题,您已经解决了这个问题。祝测试愉快!
    【解决方案2】:

    最好的方法是使用 mocha-testdata async npm 模块并传递一个文件数组来修复上述所有问题,并且所有测试用例运行良好,没有任何问题: 类似的东西

    testData = require('mocha-testdata');
    testData.async("array of files").test('#testing' , function(done, file) {
    });
    

    另外,使用 mocha suite() 代替 it(),describe() 调用。

    suite('test:', function() {
    testData.async("files array").test('#testing' , function(done, file) {
        // Code that works on the list of files
        });
    });
    

    【讨论】: