You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright Cucumber浏览器启动超时问题求助(Hook超时)

解决Playwright+Cucumber浏览器启动超时问题

问题根源

你的错误提示核心是BeforeAll钩子超时,Cucumber默认钩子超时时间为5秒。你之前的关键错误是把Cucumber的setDefaultTimeout方法放到了Playwright的launch配置参数里,这完全无效——该方法是Cucumber的API,需单独调用,不属于浏览器启动选项。

修复方案

1. 正确配置Cucumber全局超时

修改hooks.js,将setDefaultTimeout作为Cucumber API单独调用,而非传入Playwright启动配置:

const playwright = require('playwright')
const { Before, After, BeforeAll, AfterAll, setDefaultTimeout } = require('@cucumber/cucumber')

// 全局设置所有钩子、步骤的超时时间(示例设为60秒)
setDefaultTimeout(60 * 1000);

BeforeAll(async () => {
  console.log('Launch Browser')
  // 仅保留Playwright的浏览器启动配置
  global.browser = await playwright['chromium'].launch({ 
    headless: false,
    // 可选:添加启动参数加速浏览器启动
    args: ['--disable-gpu', '--no-sandbox', '--disable-dev-shm-usage']
  })
  
  console.log('before all executed')
})

AfterAll(async () => {
  console.log("Close Browser");
  await global.browser.close();
});

Before(async () => {
  console.log("Create new context and page")
  global.context = await global.browser.newContext();
  global.page = await global.context.newPage();
});

After(async () => {
  console.log("Close context and page");
  await global.page.close();
  await global.context.close();
});

2. 单独为BeforeAll钩子设置超时(可选)

若不想全局修改超时,可仅给BeforeAll钩子单独配置:

// 仅针对BeforeAll钩子设置60秒超时
BeforeAll({ timeout: 60 * 1000 }, async () => {
  console.log('Launch Browser')
  global.browser = await playwright['chromium'].launch({ headless: false })
  console.log('before all executed')
})

3. 排查浏览器启动慢的深层原因

若设置超时后仍启动失败,需检查:

  • 系统资源是否充足(CPU/内存占用过高会拖慢浏览器启动)
  • 尝试切换为headless: true模式,无头模式启动速度更快
  • 重新安装Playwright浏览器:执行npx playwright install --force清理缓存并重装
  • 关闭本地代理、VPN等可能影响网络连接的工具

内容的提问来源于stack exchange,提问作者Abhed Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 23:57:12