Cypress测试用例未保留状态,二次用例需重新登录问题
解决Cypress测试用例状态不延续问题
问题根源
- Cypress默认每个
it测试块完全隔离,会自动清除浏览器cookie、localStorage等状态 - 你的
beforeEach钩子在每个测试前都执行cy.visit跳转到登录页,强制重置页面 - 每个
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
相关产品推荐
相关产品推荐

