如何在Mocha编程调用中添加--recursive递归选项?
Got it, I've dealt with this exact scenario before! When using Mocha via its programmatic API, the --recursive CLI flag doesn't just work out of the box—you need to adjust two things: tell Mocha to enable recursive mode, and write a function to traverse all subdirectories under your test folder to load every .js test file.
Here's the step-by-step fix:
1. Enable Recursive Mode in Mocha
You can either pass the option when instantiating the Mocha object, or call the recursive() method afterwards:
- Option 1: Set during instantiation
var mocha = new Mocha({ recursive: true }); - Option 2: Call the method post-instantiation
var mocha = new Mocha(); mocha.recursive(true);
2. Recursively Traverse Test Directories
Your original code only reads files from the top-level testDir—you need a helper function to walk through all subdirectories and collect every .js test file. Add this walk function to your code:
function walk(dir, fileList = []) { const files = fs.readdirSync(dir, { withFileTypes: true }); for (const file of files) { const filePath = path.join(dir, file.name); if (file.isDirectory()) { walk(filePath, fileList); } else if (file.name.endsWith('.js')) { fileList.push(filePath); } } return fileList; }
3. Updated Full Code
Putting it all together, your code will now load all test files recursively:
var Mocha = require('mocha'), fs = require('fs'), path = require('path'); // Instantiate Mocha with recursive mode enabled var mocha = new Mocha({ recursive: true }); var testDir = 'some/dir/test'; // Helper function to recursively find all .js test files function walk(dir, fileList = []) { const files = fs.readdirSync(dir, { withFileTypes: true }); for (const file of files) { const filePath = path.join(dir, file.name); if (file.isDirectory()) { walk(filePath, fileList); } else if (file.name.endsWith('.js')) { fileList.push(filePath); } } return fileList; } // Add all found test files to Mocha walk(testDir).forEach(function(filePath) { mocha.addFile(filePath); }); // Run the tests mocha.run(function(failures){ process.on('exit', function () { process.exit(failures); // Exit with non-zero status if there were failures }); });
Why This Works
The --recursive CLI flag does two things under the hood: it tells Mocha to look for test files in all subdirectories, and it handles the directory traversal for you. When using the programmatic API, you have to implement the directory traversal yourself (with the walk function) and explicitly enable recursive mode on the Mocha instance to match the CLI behavior.
内容的提问来源于stack exchange,提问作者Majid Azimi

