fix(test): 修复沙箱环境下tabbar测试的依赖和调试flag问题
1. 移除沙箱不支持的ESM import语句 2. 内联注入依赖的_toParamValueString函数 3. 将globalThis.__TABBAR_DEBUG__替换为global以穿透沙箱 4. 修复全局调试flag无法在沙箱内生效的问题
This commit is contained in:
@@ -140,15 +140,38 @@ const TABBAR_SRC = fs.readFileSync(
|
||||
|
||||
function loadTabbarInSandbox() {
|
||||
const moduleObj = { exports: {} };
|
||||
// util-tabbar.js 通过 import 引用 util-navigate.js 的 _toParamValueString,
|
||||
// vm 沙箱里没有 import 解析, 必须先把 import 行替换掉,
|
||||
// 然后在 wrapped 源码顶部内联一份 _toParamValueString(原实现 3 行, 直接搬过来)
|
||||
// 还要把源码里 `globalThis.__TABBAR_DEBUG__` 改写成 `global.__TABBAR_DEBUG__`:
|
||||
// - 沙箱里 globalThis 是独立的 vm 上下文对象(sandbox.globalThis = sandbox),
|
||||
// 跟测试在 outer globalThis 上设的 `globalThis.__TABBAR_DEBUG__ = true` 不是同一个
|
||||
// - 改成 `global.__TABBAR_DEBUG__` 后, 沙箱的 `global` 被绑到外层 Node global,
|
||||
// 测试在 outer 写的 flag 就能被沙箱里的 checkTabBarActive 看到
|
||||
const wrapped = TABBAR_SRC
|
||||
.replace(/^export\s+function\s+/gm, 'function ')
|
||||
.replace(/^export\s+const\s+/gm, 'const ')
|
||||
.replace(/^export\s+let\s+/gm, 'let ')
|
||||
.replace(/^export\s+var\s+/gm, 'var ')
|
||||
// ESM → CJS: 删掉 import 行(vm 沙箱不支持 import)
|
||||
.replace(/^import\s+[\s\S]*?from\s+['"][^'"]+['"];?\s*$/gm, '')
|
||||
// 把 globalThis.__TABBAR_DEBUG__ 重定向到 global.__TABBAR_DEBUG__,
|
||||
// 让测试在 outer 设的 flag 能穿透进沙箱
|
||||
.replace(/globalThis\.__TABBAR_DEBUG__/g, 'global.__TABBAR_DEBUG__')
|
||||
// 在文件开头注入 _toParamValueString(util-tabbar.js 的唯一外部依赖)
|
||||
.replace(
|
||||
/^/,
|
||||
'function _toParamValueString(v) {\n'
|
||||
+ '\tif (v === null || v === undefined) return "";\n'
|
||||
+ '\tif (typeof v === "object") return JSON.stringify(v);\n'
|
||||
+ '\treturn String(v);\n'
|
||||
+ '}\n\n'
|
||||
)
|
||||
+ '\nmodule.exports = { resolvePageUrl, isPageInRouteList, resolveLinkUrl, '
|
||||
+ 'makeSystemTabBarList, adaptSubpackageUrl, isTabBarRootPage, '
|
||||
+ 'isCurrentPageTabBarRoot, checkTabBarActive, resolveEntryTab, lookupPageTabMap };\n';
|
||||
const sandbox = { console, globalThis: {}, module: moduleObj, exports: moduleObj.exports };
|
||||
// 把外层 global 注入沙箱, 配合上面的源码改写让 __TABBAR_DEBUG__ flag 穿透
|
||||
const sandbox = { console, global, globalThis: {}, module: moduleObj, exports: moduleObj.exports };
|
||||
sandbox.globalThis = sandbox;
|
||||
vm.createContext(sandbox);
|
||||
vm.runInContext(wrapped, sandbox, { filename: 'util-tabbar.js' });
|
||||
|
||||
Reference in New Issue
Block a user