【问题标题】:How to assert localStorage in Cypress如何在 Cypress 中声明 localStorage
【发布时间】:2022-01-23 15:36:57
【问题描述】:

我担心我做错了,但文档没有我找到的明确示例。

我有一个通过登录流程的测试。我还想验证我们登录后是否在 localStorage 中设置了某些值。

当我执行以下操作时,我得到一个 AssertionError,“expected null to exist”:

describe("Trying to log in...", function() {
  it("Visits the Home Page", function() {
    cy.visit("/") // Uses baseUrl prefix from config

    // [ ... snip ... ]

    // Form should be visible and fillable now!
    cy.get("form")
      .should("be.visible")
      .within(() => {
        cy.findByLabelText(/email address/i)
          .should("exist")
          .should("be.visible")
          .click() // Clicking the label should focus the element:
          .type("[test username]")
        cy.findByLabelText(/password/i)
          .click()
          .type("[test password]")
        cy.findByText(/sign in/i).click()
      })

    // Now we're logged in... 

    cy.url().should("include", "home")

    // ========= THE FOLLOWING BREAKS: =======================
    // Check for our localStorage item:
    expect(localStorage.getItem("KeyToOurValue")).to.exist()
  })
})

但是,如果我将 expect 放在最后一个 should 的回调中,它似乎可以工作吗?

describe("Trying to log in...", function() {
  it("Visits the Home Page", function() {
    cy.visit("/") // Uses baseUrl prefix from config

    // [ ... snip ... ]

    // Form should be visible and fillable now!
    cy.get("form")
      .should("be.visible")
      .within(() => {
        cy.findByLabelText(/email address/i)
          .should("exist")
          .should("be.visible")
          .click() // Clicking the label should focus the element:
          .type("[test username]")
        cy.findByLabelText(/password/i)
          .click()
          .type("[test password]")
        cy.findByText(/sign in/i).click()
      })

    // Now we're logged in... 

    cy.url().should("include", "home", ()=> {
        // ========= THE FOLLOWING WORKS! ========
        // Check for our localStorage item:
        expect(localStorage.getItem("KeyToOurValue")).to.exist()
    })
  })
})

我应该这样做吗?

看来我应该能够做到第一种方式?

在某个cy 行运行后,资产有关localStorage 值的正确方法是什么?

【问题讨论】:

    标签: javascript testing cypress


    【解决方案1】:

    你应该在 should 块中声明 localStorage 吗?是的你应该。 Check out the official example from Cypress


    对于 cy-commands (cy.put, cy.get ...),它们被 Cypress 排入队列并一个接一个地运行。另一方面,non cy-commands(期望)会立即执行。因此,如果您将 expect 留在 should() 之外,则您的 localStorage 不可用,因为 登录 尚未完成。

    通过将 expect 移动到 should 中,这意味着它在 cy.url() 完成后运行。由于 cy.url 是 Cypress 内部队列中的最后一项,因此其他 cy 命令(cy.visit、cy.get、cy.findBy...)至此已完成。

    【讨论】:

    • 非常感谢您的回答!它涵盖了在表面级别文档中不明显的内容,例如 expect 可能会进入竞争条件。对于那些精通 Javascript 测试的人来说,这可能是更一般的知识。这太棒了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-11
    • 1970-01-01
    • 2018-11-22
    • 2022-06-29
    • 1970-01-01
    相关资源
    最近更新 更多