如何在Cypress中断言localStorage

我担心我做得不正确,但是文档中没有我找到的明确示例。

我有一个遍历登录流的测试。我还想验证在登录后是否已在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()
  })
})
但是,如果我将回调中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值的内容?


解决方案

是否应在应挡路内断言localStorage?是的,你应该这样做。Check out the official example from Cypress


对于cy-Commands(cy.put,cy.get.),它们被排队,稍后由Cypress陆续运行。另一方面,会立即执行非循环命令(Expect)。因此,如果您离开Expect在Shill()之外,您的localStorage将不可用,因为登录尚未完成。

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

相关文章