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

为何Cypress beforeEach中设置的local storage在测试中不持久?

问题原因与解决方案

问题出在Cypress的异步执行顺序上:

  • cy.request是异步命令,它的.then()回调要等请求完成后才会执行,但你写的cy.visit是同步跟着cy.request之后执行的,这时候res还没被赋值,所以win.localStorage.setItem里的res.body.user其实是undefined,导致localStorage没正确设置用户信息,页面自然识别不到登录状态。

修正后的代码

把cy.visit放到cy.request的.then()回调里,确保请求完成、拿到用户数据后再访问页面并设置localStorage:

beforeEach(() => {
    cy.request({
        method: "POST",
        url: "http://localhost:3000/api/users/login",
        body: {
            "user": {
                "email":"test@test.com",
                "password":"test"
            }
        }
    }).then(response => {
        cy.visit("http://localhost:3000", {
            onBeforeLoad: function(win) {
                win.localStorage.setItem('user', JSON.stringify(response.body.user))
            }
        })
    })
})

it("Add Article", () => {
    cy.contains("New Article").click()
    cy.get("input[placeholder='Article Title']").type("Article on cypress")
    cy.get("input[placeholder='What\'s this article about?']").type("Topic is cypress")
    cy.get("[placeholder='Write your article (in markdown)']").type("Content of article")
    cy.get("input[placeholder='Enter tags']").type("Test Automation")
    cy.contains("button", "Publish Article").click()
    // 注意:原代码重复点击了两次Publish按钮,建议检查是否为笔误
})

额外验证步骤(可选)

如果还是有问题,可以在访问页面后加一步验证localStorage是否正确设置,确保数据没问题:

cy.visit(...)
cy.window().then(win => {
    const storedUser = JSON.parse(win.localStorage.getItem('user'))
    expect(storedUser.email).to.eq('test@test.com') // 验证存储的用户信息正确
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 01:18:26