Maj*_*imi 1 mocha.js node.js npm
我按照教程以编程方式运行 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
});
});
Run Code Online (Sandbox Code Playgroud)
Mocha的--recursive选项是一个命令行选项。它只能在通过命令行调用 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);
});
});
Run Code Online (Sandbox Code Playgroud)
注意:该getTestPaths函数递归地遍历目录并返回一个文件.js路径数组。
| 归档时间: |
|
| 查看次数: |
610 次 |
| 最近记录: |