调用cy.visit()打开指定页面后Cypress测试无法运行求助
Cypress访问指定站点时测试异常问题
问题现象
- 执行
cy.visit('http://tembo-urgent-care.web.app/')后,Cypress仅像普通浏览器一样打开页面,无法自动执行测试,仅支持手动交互;但切换到YouTube等其他站点时,测试可正常运行。 - 将该URL配置到Cypress配置文件后,执行
npx cypress run并选择浏览器,会直接打开目标页面,甚至无法选择要运行的测试用例。 - 执行
npx cypress open后的界面:
环境信息
- 系统:Windows 11、MacOS(仅Windows 11上的Firefox和Edge浏览器无此问题)
- Cypress版本:v12.17.3
测试脚本
describe('template spec', () => { it('"Start visit" redirects user to the form page', () => { cy.visit('https://tembo-urgent-care.web.app/'); }); });
预期结果
执行cy.visit('http://tembo-urgent-care.web.app/')后,测试能与页面正常交互。
排查与解决建议
- 检查站点CSP(内容安全策略):部分站点会限制第三方脚本注入,Cypress的测试控制依赖注入页面的代理脚本,若站点CSP禁止相关来源,会导致无法控制页面。可尝试在配置中添加
modifyObstructiveCode: false,或在cy.visit中临时调整CSP:cy.visit('https://tembo-urgent-care.web.app/', { headers: { 'Content-Security-Policy': 'default-src *' } }); - 反自动化检测规避:部分站点会识别Cypress的特征(比如全局
Cypress变量),可尝试在页面加载前移除相关标识:
也可在Cypress配置中启用cy.visit('https://tembo-urgent-care.web.app/', { onBeforeLoad(win) { delete win.Cypress; } });experimentalModifyObstructiveThirdPartyCode参数。 - 升级Cypress版本:v12.17.3版本较旧,新版本针对兼容性问题有修复,执行命令升级:
npm install cypress@latest --save-dev - 浏览器权限检查:Chrome/Safari需关闭隐私模式、允许第三方Cookie,这些设置会影响Cypress对页面的控制能力。
内容的提问来源于stack exchange,提问作者Karina
相关产品推荐
相关产品推荐

