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

Cypress v12.7.0中Chrome无头运行时跨用例会话保持失败问题

问题描述

环境信息:

  • Cypress v12.7.0
  • Chrome v112
  • Electron v106

需求:多测试用例共享登录会话,避免重复登录,使用cy.session({ cacheAcrossSpecs: true })实现跨用例会话缓存。

不同运行方式表现:

  • npx cypress open(Chrome/Electron):功能正常,第一个用例创建会话后,后续用例可恢复会话无需重复登录
  • npx cypress run(默认Electron):功能正常
  • npx cypress run --browser chrome:出现异常,流程如下:
    1. 第一个用例创建会话并执行正常
    2. 第二个用例成功恢复会话
    3. 恢复会话后执行cy.visit()跳转到登录页,而非预期的登录后页面
    4. 测试因未登录状态失败

该问题仅在Chrome无头运行模式下出现,Electron无此异常。

解决方案尝试

1. 显式在会话中保存关键认证数据

在cy.session的setup函数中,完成登录后显式保存认证相关的cookie或localStorage数据,确保恢复会话时能正确加载:

cy.session('user-login', () => {
  // 执行登录流程
  cy.visit('/login')
  cy.get('#username').type('test-user')
  cy.get('#password').type('test-pass')
  cy.get('#submit').click()
  // 保存认证cookie和localStorage数据
  cy.getCookie('auth-token').then(cookie => {
    Cypress.env('authToken', cookie.value)
  })
  cy.window().then(win => {
    Cypress.env('userSession', win.localStorage.getItem('user-session'))
  })
}, { 
  cacheAcrossSpecs: true,
  // 验证会话有效性
  validate: () => {
    cy.visit('/dashboard')
    cy.get('.user-profile').should('exist')
  }
})

恢复会话后手动注入认证数据:

cy.session('user-login', null, { cacheAcrossSpecs: true })
// 注入保存的认证信息
cy.setCookie('auth-token', Cypress.env('authToken'))
cy.window().then(win => {
  win.localStorage.setItem('user-session', Cypress.env('userSession'))
})
cy.visit('/dashboard')

2. 调整Chrome启动参数

在cypress.config.js中添加Chrome启动参数,优化无头模式下的cookie和隐私策略:

const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser = {}, launchOptions) => {
        if (browser.name === 'chrome' && browser.isHeadless) {
          // 禁用隐私沙盒相关特性
          launchOptions.args.push('--disable-features=PrivacySandboxSettings4')
          // 允许第三方cookie(若认证依赖此)
          launchOptions.args.push('--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure')
          launchOptions.args.push('--no-first-run')
          launchOptions.args.push('--no-default-browser-check')
        }
        return launchOptions
      })
    },
  },
})

3. 禁用Chrome Web Security

若应用存在跨域认证场景,可尝试在Cypress配置中禁用Chrome的Web安全:

module.exports = defineConfig({
  e2e: {
    chromeWebSecurity: false,
  },
})

注意:此设置仅适用于测试环境,生产环境禁止使用。

4. 升级Chrome版本

Chrome v112可能存在无头模式下的会话缓存兼容性问题,尝试升级至v114及以上版本,验证问题是否解决。

5. 优化会话验证逻辑

确保cy.session的validate函数能准确判断会话有效性,避免误判:

cy.session('user-login', () => {
  // 登录操作
}, {
  cacheAcrossSpecs: true,
  validate: () => {
    // 直接调用认证接口验证状态,比页面元素检查更可靠
    cy.request('/api/user/profile').its('status').should('eq', 200)
  }
})

内容的提问来源于stack exchange,提问作者Asier Pérez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 21:07:19