Cypress导航测试禁用testIsolation后会话重置异常求助
解决方案
方案一:修复testIsolation禁用后的清理逻辑
你禁用testIsolation: false后,整个测试套件的上下文会被保留,包括浏览器会话。重新运行测试时,before块只在套件启动时执行一次,之前的会话缓存没被清掉,所以会出现登录状态残留。
需要在测试套件结束后添加清理逻辑,同时调整before里的清理顺序(先清理所有存储,再访问网站):
describe("Navigation Suite ", { testIsolation: false }, () => { before(() => { // 先彻底清理存储,再执行登录 cy.clearAllCookies(); cy.clearAllLocalStorage(); cy.clearAllSessionStorage(); cy.viewport(1920, 900); cy.gotoWebsite(); cy.loginWebsite(); }); // 测试套件结束后清理状态,保证重新运行时环境干净 after(() => { cy.clearAllCookies(); cy.clearAllLocalStorage(); cy.clearAllSessionStorage(); cy.visit("/logout"); // 如果网站有登出接口,最好主动登出 }); it("should navigate to Clients", () => { cy.sideMenuCustomerServices("https://localhost/client"); }); it("should navigate to Records", () => { cy.sideMenuVatRegistration("https://localhost/records/client"); }); it("should navigate to Returns", () => { cy.sideMenuVatReturns("https://localhost/returns"); }); });
另外注意:代码里cy.clearAllLocalStorage()写了两次,去掉重复项即可。
方案二:使用Cypress Session持久化登录(推荐)
Cypress自带的cy.session()专门解决重复登录问题,不需要禁用testIsolation,既能保证每个测试的独立性,又能避免重复登录的开销。
把登录逻辑封装到cy.session里,在beforeEach中调用:
describe("Navigation Suite ", () => { beforeEach(() => { cy.viewport(1920, 900); // 用session管理登录状态 cy.session("user-login", () => { cy.clearAllCookies(); cy.clearAllLocalStorage(); cy.gotoWebsite(); cy.loginWebsite(); }, { // 配置会话验证逻辑,确保登录状态有效 validate() { cy.get("nav.user-profile").should("be.visible"); // 假设登录后会显示用户头像导航 } }); // 每次测试前回到首页,避免上一个测试的页面状态影响当前测试 cy.gotoWebsite(); }); it("should navigate to Clients", () => { cy.sideMenuCustomerServices("https://localhost/client"); }); it("should navigate to Records", () => { cy.sideMenuVatRegistration("https://localhost/records/client"); }); it("should navigate to Returns", () => { cy.sideMenuVatReturns("https://localhost/returns"); }); });
这个方案的优势:
- 每个测试仍保持隔离,不会互相污染状态
- 只在第一次运行或会话失效时执行登录,提升测试速度
- 不需要手动处理存储清理,Cypress会自动管理会话
方案三:单测试用例拆分步骤(适合依赖顺序的导航)
如果你的导航流程是有顺序依赖的(比如必须先进入Clients才能到Records),可以把所有导航步骤放到一个it里,用cy.step()拆分,既保证流程连贯,又能在测试报告里看到清晰的步骤:
describe("Navigation Suite ", () => { beforeEach(() => { cy.viewport(1920, 900); cy.gotoWebsite(); cy.loginWebsite(); }); it("should navigate through all sidebar tabs", () => { cy.step("Navigate to Clients"); cy.sideMenuCustomerServices("https://localhost/client"); cy.step("Navigate to Records"); cy.sideMenuVatRegistration("https://localhost/records/client"); cy.step("Navigate to Returns"); cy.sideMenuVatReturns("https://localhost/returns"); }); });
这个方案适合导航流程有强顺序的场景,避免测试之间的状态依赖问题。
内容的提问来源于stack exchange,提问作者Adrián Núñez Martínez
相关产品推荐
相关产品推荐

