如何使用 Cypress 检查 sessionStorage 的值

8

我刚开始接触cypress.io,正在尝试检查sessionStorage是否被设置了。

如何检查sessionStorage中的项目是否存在?


我试过调用:cy.wrap(sessionStorage.getItem('someItem')).should('exist');,但它似乎是在初始化时设置的值,因为第一个测试说它期望是 null,而在另一个测试中它期望是旧的sessionStorage值(来自以前的测试)。

it('can set sessionItem', function() {
   cy.visit('/handlerUrl')
   // ... some code
   cy.get('[type=submit]').click()
   cy.url().should('include', '/anotherUrl')
   cy.wrap(sessionStorage.getItem('someItem')).should('exist');
})
2个回答

16

您也可以使用

cy.window()
  .its("sessionStorage")
  .invoke("getItem", "token")
  .should("exist");

由于某些原因,在我的情况下这不起作用。 - keul

6

我不得不使用cy.window(),它可以获取当前处于活动状态的页面的窗口对象。

cy.window().then(win=> {
  const someItem = win.sessionStorage.getItem('someItem')
  cy.wrap(someItem).should('exist') // or 'not.empty'
}); 

可以在cypress.io文档中找到有关cy.window()的更多信息。


仍然无法工作,someItem 仍为空。 - ksk
那很可能不是Cypress的问题,因为文档仍然提到Windows,在我的情况下它仍然有效。 - Jax-p

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接