/** * 测试CommonJS格式的监控SDK bundle */ // 在Node.js环境中测试CJS格式的bundle console.log("开始测试CommonJS格式的监控SDK"); try { // 动态引入CJS格式的bundle const MonitorSDK = require("../dist/bundle-cjs.js"); console.log("CommonJS格式的监控SDK已加载"); console.log("MonitorSDK类型:", typeof MonitorSDK); // 注意:由于Node.js环境缺少浏览器API(如window、document、performance等) // 直接初始化可能会出错,所以我们只测试基本导入功能 // 检查MonitorSDK构造函数是否存在 if (typeof MonitorSDK === "function") { console.log("✅ MonitorSDK构造函数存在"); } else { console.log("❌ MonitorSDK不是函数"); } console.log("\n注意:由于Node.js环境缺少浏览器API,完整的SDK功能无法在此环境中测试。"); console.log("完整的功能测试需要在浏览器环境中进行。"); } catch (error) { console.error("❌ 加载CommonJS格式的bundle时出错:", error.message); } // 模拟浏览器环境的部分功能以测试SDK console.log("\n--- 模拟浏览器环境测试 ---"); // 为Node.js环境模拟必要的浏览器API global.window = global; global.document = { addEventListener: function (event, handler) { console.log(`模拟添加${event}事件监听器`); }, }; global.performance = { timing: { navigationStart: Date.now(), domainLookupStart: Date.now(), domainLookupEnd: Date.now() + 1, connectStart: Date.now() + 1, connectEnd: Date.now() + 2, requestStart: Date.now() + 2, responseStart: Date.now() + 3, responseEnd: Date.now() + 4, domLoading: Date.now() + 5, domContentLoadedEventStart: Date.now() + 6, domContentLoadedEventEnd: Date.now() + 7, loadEventStart: Date.now() + 8, loadEventEnd: Date.now() + 9, }, getEntriesByType: function (type) { console.log(`模拟获取${type}类型的性能条目`); return []; }, }; global.navigator = { userAgent: "Test Node Environment", sendBeacon: function (url, data) { console.log("模拟sendBeacon调用:", url, data); return true; }, }; global.fetch = function (url, options) { console.log("模拟fetch调用:", url, options); return Promise.resolve({ ok: true, json: () => Promise.resolve({}), }); }; // 现在尝试动态加载并初始化SDK setTimeout(() => { try { // 重新require以确保使用新的全局变量 delete require.cache[require.resolve("../dist/bundle-cjs.js")]; const MonitorSDK = require("../dist/bundle-cjs.js"); // 创建实例 const monitor = new MonitorSDK({ appId: "test-app", apiUrl: "http://localhost:3000/api/monitor", enableErrorTracking: true, enablePerformanceTracking: true, enableUserBehaviorTracking: false, // 避免在Node.js中使用document enableResourceTracking: true, sampleRate: 1.0, }); console.log("✅ 成功创建MonitorSDK实例"); // 测试错误上报功能 if (monitor && typeof monitor.reportError === "function") { console.log("✅ reportError方法存在"); monitor.reportError({ type: "test_error", message: "测试错误", timestamp: Date.now(), }); console.log("✅ 成功调用reportError方法"); } else { console.log("❌ reportError方法不存在"); } // 测试数据上报功能 if (monitor && typeof monitor.reportData === "function") { console.log("✅ reportData方法存在"); monitor.reportData({ type: "test_data", message: "测试数据", timestamp: Date.now(), }); console.log("✅ 成功调用reportData方法"); } else { console.log("❌ reportData方法不存在"); } } catch (error) { console.error("❌ 在模拟环境中初始化SDK时出错:", error.message); console.error("堆栈:", error.stack); } }, 100);