From cd2705e5b9453a23f885bbfe7732c93c37324227 Mon Sep 17 00:00:00 2001 From: ZF sun <34314687@qq.com> Date: Sat, 18 Jul 2026 18:31:00 +0800 Subject: [PATCH] =?UTF-8?q?fix(test):=20=E4=BF=AE=E5=A4=8D=E6=B2=99?= =?UTF-8?q?=E7=AE=B1=E7=8E=AF=E5=A2=83=E4=B8=8Btabbar=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=9A=84=E4=BE=9D=E8=B5=96=E5=92=8C=E8=B0=83=E8=AF=95flag?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. 移除沙箱不支持的ESM import语句 2. 内联注入依赖的_toParamValueString函数 3. 将globalThis.__TABBAR_DEBUG__替换为global以穿透沙箱 4. 修复全局调试flag无法在沙箱内生效的问题 --- tests/tabbar-highlight.test.js | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/tests/tabbar-highlight.test.js b/tests/tabbar-highlight.test.js index 54bc284..bc24dfe 100644 --- a/tests/tabbar-highlight.test.js +++ b/tests/tabbar-highlight.test.js @@ -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' });