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

Cypress测试用例未保留状态,二次用例需重新登录问题

解决Cypress测试用例状态不延续问题

问题根源

  1. Cypress默认每个it测试块完全隔离,会自动清除浏览器cookie、localStorage等状态
  2. 你的beforeEach钩子在每个测试前都执行cy.visit跳转到登录页,强制重置页面
  3. 每个it块内重复编写登录逻辑,进一步导致状态无法延续

解决方案

1. 全局一次性登录,共享状态

将登录逻辑移到before钩子(整个测试套件仅执行一次),配合Cookie保留机制,让登录状态在测试用例间延续。

2. 调整页面初始化逻辑

beforeEach不再跳转登录页,改为直接进入目标业务页面,避免重复初始化。

修改后的代码示例

describe('CMS Department', () => {

  // 所有测试执行前仅登录一次
  before(() => {
    cy.visit('https://whitecode.biz/staging/cms/admin');
    
    Cypress.on('uncaught:exception', (err, runnable) => {
      return false;
    });

    cy.fixture('cmslogin').then((data) => {
      const login = new Department();
      login.setEmail(data.email);
      login.setPassword(data.password);
      login.clickSignIn();
      
      // 等待登录完成,验证跳转至后台页面
      cy.url().should('include', '/dashboard'); // 根据实际后台URL调整
    });

    // 保留登录相关Cookie,避免测试间被清除
    Cypress.Cookies.preserveOnce('auth-token'); // 替换为实际登录Cookie名称
  });

  beforeEach(() => {
    // 每个测试前直接进入部门管理页面
    cy.visit('https://whitecode.biz/staging/cms/admin/departments'); // 替换为实际部门页URL
    Cypress.on('uncaught:exception', (err, runnable) => {
      return false;
    });
  });
  
  it('Add_Dept_Possitive_Scenario', () => {
    const dept = new Department();
    dept.Add_New_Dept();
    dept.Breadcrum_Image();
    dept.Faculty_Select("1");
    dept.Department_Name("Re-department");
    dept.Show_On_Website();
    dept.Add_Department();
  });

  it('Edit_Department', () => {
    const dept = new Department();
    dept.Edit_Record();
  });
});

补充配置(可选)

如果需要全局保留登录Cookie,可在cypress.config.js中添加配置,替代preserveOnce:

module.exports = defineConfig({
  e2e: {
    // ...其他配置
    cookies: {
      preserve: ['auth-token'] // 替换为实际登录Cookie名称
    }
  }
});

内容的提问来源于stack exchange,提问作者Shubham Jadhav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 03:55:07