如何在 Cypress 中声明 localStorage

ano*_*ard 5 javascript testing cypress

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

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

当我执行以下操作时,我收到一个 AssertionError,“预期存在空值”:

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()
  })
})
Run Code Online (Sandbox Code Playgroud)

但是,如果我把它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()
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

我应该这样做吗?

似乎我应该能够以第一种方式做到这一点?

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

Hun*_*ran 9

你应该在 should 块内断言 localStorage 吗?是的你应该。查看 Cypress 的官方示例


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

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

  • 链接不再有效 (5认同)