如何以编程方式向mocha添加递归选项?

时间:2018-01-19 09:49:55

标签: node.js npm mocha

我按照tutorial以编程方式运行mocha。但是,当我使用--recursive进行测试时,我无法弄清楚如何添加npm test我可以添加的选项。

var Mocha = require('mocha'),
    fs = require('fs'),
    path = require('path');

// Instantiate a Mocha instance.
var mocha = new Mocha();

var testDir = 'some/dir/test'

// Add each .js file to the mocha instance
fs.readdirSync(testDir).filter(function(file){
    // Only keep the .js files
    return file.substr(-3) === '.js';

}).forEach(function(file){
    mocha.addFile(
        path.join(testDir, file)
    );
});

// Run the tests.
mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);  // exit with non-zero status if there were failures
  });
});

1 个答案:

答案 0 :(得分:4)

--recursiveMocha选项是命令行选项。它只能在通过命令行调用Mocha时应用,即使用以下用法语法时:

  

Usage: mocha [debug] [options] [files]

您的节点脚本中当前的fs.readdirSync()实现不会递归获取.js个测试文件。它只获取目录顶层的路径。

fs.readdirSync()没有提供递归读取目录的选项。

考虑编写一个递归获取.js测试文件的自定义函数。

例如:

var fs = require('fs'),
    path = require('path'),
    Mocha = require('mocha');

// Instantiate a Mocha instance.
var mocha = new Mocha();

var testDir = 'path/to/test/files/';

/**
 * Gets the test .js file paths recursively from a given directory.
 * @param {String} dir - path to directory containing test files.
 * @returns {Array} Filepaths to each test .js file.
 */
function getTestPaths(dir, fileList) {
    var files = fs.readdirSync(dir);
    fileList = fileList || [];

    files.forEach(function(file) {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
            fileList = getTestPaths(path.join(dir, file), fileList);
        } else {
            fileList.push(path.join(dir, file));
        }
    });

    return fileList.filter(function (file) {
        return path.extname(file) === '.js';
    });
}

// Get all .js paths and add each file to the mocha instance.
getTestPaths(testDir).forEach(function(file) {
    mocha.addFile(
        path.join(file)
    );
});

// Run the tests.
mocha.run(function(failures) {
    process.on('exit', function () {
        process.exit(failures);
    });
});

注意: getTestPaths函数以递归方式遍历目录并返回.js个文件路径数组。