使用Jest结合rewire时window.location未定义问题排查
排查Jest+rewire场景下window.location未定义问题
以下是针对你遇到问题的具体排查建议:
确认模块执行时机与window环境绑定
url-manipulator.js的顶层代码(sHost: 'https://' + window.location.host)会在模块被加载的瞬间执行。虽然你在测试代码里打印window.location正常,但rewire加载模块时可能未正确继承Jest的jsdom环境。可以尝试在加载该模块前,显式把window挂载到全局:// 在rewire加载url-manipulator之前添加 global.window = window; global.location = window.location; const urlManipulatorJS = rewire("../../../head/js/url-manipulator");手动初始化window.location对象
有时候Jest的testEnvironmentOptions配置可能没有在模块加载前生效,你可以手动构造location对象:window.location = new URL('https://www.something.com'); // 再加载模块 const urlManipulatorJS = rewire("../../../head/js/url-manipulator");替换rewire为Jest原生mock
rewire的模块加载逻辑可能和Jest的jsdom环境存在兼容性问题,改用Jest的mock功能直接模拟url-manipulator模块,避免执行真实模块的顶层代码:// 放在测试文件最顶部 jest.mock('../../../head/js/url-manipulator', () => ({ urlManipulator: { sHost: 'https://www.something.com' } })); // 正常导入some-file即可,它会自动使用mock的模块 const { someFile } = require("../some-file");检查版本兼容性
旧版本的rewire(比如rewire@5.x及以下)可能和Jest 28+的jsdom环境不兼容,导致模块加载时无法获取window对象。尝试升级rewire到最新稳定版,或者降级Jest到兼容版本测试。排查模块全局污染
检查url-manipulator.js或其依赖的其他模块,是否有代码在加载时修改/清空window对象,导致顶层代码执行时window变为undefined。
内容的提问来源于stack exchange,提问作者Dustin
相关产品推荐
相关产品推荐

