WSL2中配置Cypress测试Vite+Vue3应用遇连接超时等问题求助
问题:Cypress测试Vite+Vue3应用时浏览器连接超时及启动报错
现象
执行npx cypress open时出现以下错误:
[26403:0310/094751.006561:ERROR:udev_watcher.cc(63)] Failed to enable receiving udev events. [26560:0310/094751.074840:ERROR:gpu_memory_buffer_support_x11.cc(44)] dri3 extension not supported.
已安装依赖包:
apt-get install libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb
并使用xlaunch,但问题未解决。改用npx cypress run时,出现浏览器连接超时:
Timed out waiting for the browser to connect. Retrying... Timed out waiting for the browser to connect. Retrying again... The browser never connected. Something is wrong. The tests cannot run. Aborting... The browser never connected. Something is wrong. The tests cannot run. Aborting...
配置文件
cypress.config.ts
import { defineConfig } from 'cypress'; export default defineConfig({ e2e: { baseUrl: 'http://localhost:3100', specPattern: 'tests/e2e/specs/*.e2e.ts', supportFile: false }, component: { devServer(cypressConfig) { return { port: 8081, close: () => {} }; }, specPattern: 'tests/e2e/specs/*.e2e.ts', viewportWidth: 1000, viewportHeight: 900 }, env: { apiUrl: 'http://localhost:3100', dbUrl: 'postgresql://user:password@localhost:5432/db_test?connect_timeout=300' }, video: false, screenshotOnRunFailure: false });
demo.e2e.ts
describe('Demo', () => { it('increments counter when button is clicked', () => { cy.visit('/'); cy.contains('Click me! (0)').click(); cy.contains('Click me! (1)'); }); });
解决方案
1. 修正组件测试DevServer配置
当前component测试的devServer配置无效,Cypress需要绑定正确的Vite开发服务配置。替换component段配置为:
component: { devServer: { framework: 'vue', bundler: 'vite', // 若有自定义Vite配置文件,可添加路径 // configFile: './vite.config.ts' }, specPattern: 'tests/e2e/specs/*.e2e.ts', viewportWidth: 1000, viewportHeight: 900 },
2. 禁用GPU硬件加速解决X11报错
针对dri3扩展和udev事件错误,强制Cypress使用软件渲染:
- 执行命令时添加环境变量:
CYPRESS_GPU_ACCELERATION=false npx cypress open # 运行模式 CYPRESS_GPU_ACCELERATION=false npx cypress run
- 或在配置文件中添加浏览器启动参数:
export default defineConfig({ // ...其他配置 e2e: { // ...其他e2e配置 setupNodeEvents(on, config) { on('before:browser:launch', (browser = {}, launchOptions) => { if (browser.family === 'chromium' && browser.name !== 'electron') { launchOptions.args.push('--disable-gpu'); launchOptions.args.push('--no-sandbox'); launchOptions.args.push('--disable-dev-shm-usage'); return launchOptions; } }); } } });
3. 确保应用服务提前启动
执行测试前,先启动Vite应用:
npm run dev
确认http://localhost:3100可正常访问后,再运行Cypress。
4. 调整超时阈值(可选)
若因服务启动慢导致超时,在e2e配置中延长超时时间:
e2e: { // ...其他配置 browserLaunchTimeout: 120000, // 2分钟 pageLoadTimeout: 60000 },
内容的提问来源于stack exchange,提问作者Thắng Nguyễn Quyết
相关产品推荐
相关产品推荐

