我有一个类似的问题,有十几个模块,最终我使用了mock-require。
我创建了一个小模块来遍历包含所有模块的目录,并对它们进行模拟。
这个模块叫做"@my-scope/mockModules"。
const fs = require("fs-extra")
const path = require("path")
const mockRequire = require("mock-require")
function traverseDir(directory, options, callback) {
const files = fs.readdirSync(directory)
for(const file of files) {
const filepath = path.join(directory, file)
const stat = fs.statSync(filepath)
if (stat.isDirectory()) {
if (options.exclude_folders === undefined || options.exclude_folders.indexOf(file) === -1) {
traverseDir(filepath, options, callback)
}
} else {
callback(file, filepath, directory)
}
}
}
function getPackages(root) {
const packages = []
traverseDir(root, {
exclude_folders: ["node_modules"]
}, (name, path, directory) => {
if(name === "package.json") {
try {
const content = require(path)
packages.push({
path,
directory,
content
})
} catch(error) {
console.error(`could not open ${path}`)
}
}
})
return packages
}
function mockModules(rootFolder, scope) {
let packages = getPackages(`${__dirname.split(rootFolder)[0]}${rootFolder}`)
packages = packages.filter(pack => pack.content.name.indexOf(`${scope}/`) == 0)
console.log("mocking")
for(const pack of packages) {
const path = `${pack.directory}/${pack.content.main}`
console.log(` ${pack.content.name} ${path}`)
mockRequire(pack.content.name, path)
}
}
module.exports = mockModules
这是如何使用它的:
const mockModules = require("@my-scope/mockModules")
mockModules("my-scope", "name of root folder")