Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check sessionStorage value with Cypress

Tags:

cypress

I'm new to cypress.io and I'm trying to check if item in sessionStorage is being set.

How do I check if item in sessionStorage exists?


I've tried it by calling: cy.wrap(sessionStorage.getItem('someItem')).should('exist'); but it looks like the value is being set on initialization because at the first test it says it expected null and in another test it expects old sessionStorage value (from previous test).

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');
})
like image 716
Jax-p Avatar asked Dec 05 '19 10:12

Jax-p


2 Answers

You can also use

cy.window()
  .its("sessionStorage")
  .invoke("getItem", "token")
  .should("exist");
like image 176
Diogo Mafra Avatar answered Sep 22 '22 19:09

Diogo Mafra


I had to use cy.window() which can get the window object of the page that is currently active.

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

More information about cy.window() can be found in cypress.io documentation.

like image 41
Jax-p Avatar answered Sep 26 '22 19:09

Jax-p