jest fs 寫自定義 collectCoverageFrom 指定檔案 檢查測試覆蓋率上
阿新 • • 發佈:2018-12-26
const fs = require('fs'); const path = require('path'); //讀取指定資料夾下的全部檔案,可通過正則進行過濾,返回檔案路徑陣列 function readAllFile(root, reg, aaa) { var resultArr = []; if (fs.existsSync(root)) { var stat = fs.lstatSync(root); if (stat.isDirectory()) { var files = fs.readdirSync(root); files.forEach(function (file) { var t = readAllFile(root + '/' + file, reg); resultArr = resultArr.concat(t); }); } else { if (reg !== undefined) { if (typeof reg.test == 'function' && reg.test(root)) { resultArr.push(root); } } else { resultArr.push(root); } } } return resultArr; } //獲取除去node_modules 後的檔案路徑陣列 //filePath 如果是正則 就匹配正則 是路徑 就匹配路徑 const readAllFileList = (fileList, testReg) => { if (fileList.length) { const result = fileList.reduce((target, file) => { const { filePath, ExtensionName } = file; let files = []; if (filePath instanceof RegExp == false && typeof filePath !== 'string') { console.log('filePath屬性只能是:string || RegExp') return false; } else if (filePath instanceof RegExp) { const noNodeModulesFiles = readAllFile(path.resolve(__dirname, '../'), /^((?!node_modules).)*$/); files = noNodeModulesFiles .filter(noNodeModuleFile => filePath.test(noNodeModuleFile)) .filter(file => testReg.test(file)); } else { files = readAllFile(path.resolve(__dirname, filePath), testReg) } const collectList = files.map(path => path.split('creams-main/')[1].split('/__tests')[0] + ExtensionName) target = target.concat(collectList); return target; },[]) return result; } else { const noNodeModulesFiles = readAllFile(path.resolve(__dirname, '../'), /^((?!node_modules).)*$/); return noNodeModulesFiles .filter(file => testReg.test(file)) .map(path => path.split('creams-main/')[1].split('/__tests')[0] + '/**/*.{ts,tsx}'); } } module.exports = readAllFileList;
//獲取自定義 指定檢查所有需要測試的檔案 不配置是預設
const fileList = []
var testReg = /__tests__/;
const collectCoverageFrom = [...new Set(readAllFileList(fileList, testReg))];