#!/usr/bin/env node /** * Playwright 前端测试脚本 - 检查姓名管理页面 */ const { chromium } = require('playwright'); async function runPlaywrightTest() { console.log('🎭 启动Playwright测试 - 检查姓名管理页面...\n'); let browser; let page; try { // 启动浏览器 browser = await chromium.launch({ headless: false, // 设置为false以便观察 slowMo: 500 // 减慢操作速度以便观察 }); const context = await browser.newContext({ viewport: { width: 1280, height: 800 } }); page = await context.newPage(); // 设置请求监听,捕获API调用 page.on('request', request => { if (request.url().includes('/nameTemplate/') || request.url().includes('/firstname/') || request.url().includes('/lastname/')) { console.log(`📤 API请求: ${request.method()} ${request.url()}`); } }); page.on('response', response => { if (response.url().includes('/nameTemplate/') || response.url().includes('/firstname/') || response.url().includes('/lastname/')) { console.log(`📥 API响应: ${response.status()} ${response.url()}`); } }); // 访问前端页面(运行在8891端口) console.log('🌐 正在访问前端页面...'); try { await page.goto('http://localhost:8891', { waitUntil: 'networkidle', timeout: 10000 }); console.log('✅ 前端页面加载成功'); } catch (error) { console.log('❌ 前端页面访问失败,尝试其他端口...'); // 尝试其他常见端口 const ports = [8080, 8081, 3000, 3001, 4000, 5000, 8890, 8892]; let connected = false; for (const port of ports) { try { await page.goto(`http://localhost:${port}`, { waitUntil: 'networkidle', timeout: 5000 }); console.log(`✅ 在端口 ${port} 找到前端页面`); connected = true; break; } catch (e) { console.log(`❌ 端口 ${port} 无法访问`); } } if (!connected) { throw new Error('无法找到运行中的前端服务'); } } // 等待页面内容加载 await page.waitForTimeout(2000); // 检查页面标题 const title = await page.title(); console.log(`📝 页面标题: ${title}`); // 尝试查找姓名管理相关的导航或页面元素 console.log('\n🔍 查找姓名管理相关元素...'); // 查找可能的导航菜单 const menuItems = await page.$$eval('*', elements => { return elements .filter(el => { const text = el.textContent || ''; return text.includes('姓名') || text.includes('名字') || text.includes('firstname') || text.includes('lastname'); }) .map(el => ({ tagName: el.tagName, text: el.textContent?.trim(), className: el.className, href: el.href || null })) .slice(0, 10); // 限制结果数量 }); if (menuItems.length > 0) { console.log('✅ 找到姓名管理相关元素:'); menuItems.forEach((item, index) => { console.log(` ${index + 1}. ${item.tagName}: "${item.text}" (class: ${item.className})`); }); // 尝试点击第一个相关元素 try { const firstItem = menuItems[0]; if (firstItem.text) { console.log(`\n🖱️ 尝试点击: "${firstItem.text}"`); await page.click(`text=${firstItem.text}`); await page.waitForTimeout(2000); console.log('✅ 成功点击元素'); // 检查是否有数据加载 await page.waitForTimeout(3000); // 查找表格或列表数据 const hasTable = await page.$('table') !== null; const hasList = await page.$('[class*="list"]') !== null; const hasCards = await page.$('[class*="card"]') !== null; console.log(`📊 页面内容检查:`); console.log(` - 包含表格: ${hasTable}`); console.log(` - 包含列表: ${hasList}`); console.log(` - 包含卡片: ${hasCards}`); // 截取屏幕截图 await page.screenshot({ path: 'name_management_page.png', fullPage: true }); console.log('📸 屏幕截图已保存: name_management_page.png'); } } catch (clickError) { console.log(`❌ 点击失败: ${clickError.message}`); } } else { console.log('❌ 未找到姓名管理相关元素'); // 获取页面的主要内容 const bodyText = await page.$eval('body', el => el.textContent?.substring(0, 500)); console.log(`📄 页面主要内容预览:\n${bodyText}...`); } // 检查控制台错误 console.log('\n🔍 检查控制台错误...'); page.on('console', msg => { if (msg.type() === 'error') { console.log(`❌ 控制台错误: ${msg.text()}`); } }); // 检查网络错误 page.on('requestfailed', request => { console.log(`❌ 网络请求失败: ${request.url()} - ${request.failure()?.errorText}`); }); // 等待一段时间以观察页面 await page.waitForTimeout(5000); } catch (error) { console.error('❌ Playwright测试失败:', error.message); if (page) { // 尝试截取错误页面 try { await page.screenshot({ path: 'error_page.png', fullPage: true }); console.log('📸 错误页面截图已保存: error_page.png'); } catch (screenshotError) { console.log('❌ 无法保存错误截图'); } } } finally { if (browser) { await browser.close(); } console.log('\n🎭 Playwright测试完成'); } } // 检查Playwright是否已安装 async function checkPlaywrightInstallation() { try { require('playwright'); return true; } catch (error) { console.log('❌ Playwright未安装,正在安装...'); const { spawn } = require('child_process'); return new Promise((resolve, reject) => { const install = spawn('npm', ['install', 'playwright'], { stdio: 'inherit', cwd: process.cwd() }); install.on('close', (code) => { if (code === 0) { console.log('✅ Playwright安装成功'); resolve(true); } else { reject(new Error(`Playwright安装失败,退出码: ${code}`)); } }); }); } } // 主函数 if (require.main === module) { checkPlaywrightInstallation() .then(() => runPlaywrightTest()) .catch(error => { console.error('❌ 测试运行失败:', error.message); process.exit(1); }); } module.exports = runPlaywrightTest;