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

Cypress E2E测试中cypress-localstorage-commands失效致登录跳转异常

问题分析与解决方案

问题概述

你的React应用包含登录页和仪表盘页,仅登录成功后可访问仪表盘,认证令牌存储在localStorage中。使用cypress-localstorage-commands工具希望实现单次登录复用认证状态,但测试时登录后跳转仪表盘,等待3000ms后自动退回登录页,导致断言contains Products失败,提示assert expected undefined to exist in the DOM。

使用版本

  • Cypress 12.17.2
  • cypress-localstorage-commands 2.2.4

解决步骤

1. 替换固定等待为登录成功断言

你的login命令使用cy.wait(3000)做固定等待,这会导致测试不稳定,应替换为验证登录成功的断言,确保页面完全跳转后再执行后续操作:
修改cypress/support/commands.ts中的登录命令:

Cypress.Commands.add("login", (email = "admin@gmail.com", password = "admin") => {
  cy.visit("http://localhost:3000/login");
  
  cy.get("input[name=\"email\"]").type(email);
  cy.get("input[name=\"password\"]").type(password);
  cy.get("button[type=\"submit\"]").click();

  // 断言URL跳转到仪表盘,替换为你的实际仪表盘路径
  cy.url().should("include", "/dashboard");
  // 或直接断言仪表盘专属元素可见,确认登录完成
  cy.contains("Products").should("be.visible");
});

2. 调整localStorage快照的保存与恢复逻辑

确保登录后正确保存localStorage快照,且在每次测试前恢复后再访问页面,避免页面加载时无认证信息被重定向:
修改cypress/e2e/dashboard.ts:

describe("Dashboard Page", () => {
  before(() => {
    cy.clearLocalStorageSnapshot();
    cy.login();
    // 登录成功后手动保存localStorage快照
    cy.saveLocalStorage();
  });
  
  beforeEach(() => {
    cy.restoreLocalStorage();
    cy.visit(ANALYTICS_PATH);
    // 验证页面未被重定向至登录页
    cy.url().should("include", ANALYTICS_PATH);
  });

  afterEach(() => {
    cy.saveLocalStorage();
  });

  it("should navigate to the dashboard page and see its content", () => {
    cy.contains("Products").should("exist");
    cy.contains("Number of Products").should("exist");
    cy.contains("Carts").should("exist");
  });
});

3. 验证认证令牌的存储状态

在登录命令中添加验证,确保localStorage中正确存储了认证令牌,避免应用无法读取令牌导致重定向:

// 在login命令末尾添加
cy.window().then(window => {
  // 替换为你的应用实际存储令牌的键名
  expect(window.localStorage.getItem("authToken")).to.exist;
});

4. 排查应用路由守卫逻辑

页面自动退回登录页,大概率是应用的路由守卫未正确读取localStorage中的令牌。可以在测试中添加日志,查看localStorage恢复后的状态:

beforeEach(() => {
  cy.restoreLocalStorage();
  cy.window().then(window => {
    console.log("恢复后的localStorage:", window.localStorage);
  });
  cy.visit(ANALYTICS_PATH);
});

内容的提问来源于stack exchange,提问作者Demo Guy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 01:05:22