Home > OS >  Cypress: Add option to allow LocalStorage
Cypress: Add option to allow LocalStorage

Time:02-17

The following facts:

  1. page 'X' Open -> cy.visit('/projects');
  2. check checkbox 'A'-> cy.checkCheckbox('A');
  3. close browser or reopen page ??????
  4. check if checkbox 'A' is still checked cy.VerifyCheckBox('A', 'checked');

To step 3: If I only use the command 'cy.visit('X);' then Cypress clears the cache and my customisations are lost.

I know that there is a command 'Cypress.LocalStorage', but I don't know how exactly to use it for my case.

Thanks for your help!

CodePudding user response:

I believe you can visit your page, set the local storage value, and then validate the checkbox. Roughly, it would look like:

cy.visit('/projects');
cy.window().then((window) => {
  window.localStorage.setItem('myLocalStorageItem', value);
})
cy.VerifyCheckBox('A', 'checked');

It doesn't mimic an exact user's workflow, but it works the same overall -- the checkbox is checked when a localStorage item is set to some value.

CodePudding user response:

I would follow the pattern that @agoff uses, but use window:before:load event.

That way will catch any regression that clears the value during page load.

// verify that CheckboxA sets local storage
cy.visit('/projects')
cy.checkCheckbox('A')
cy.window().then((window) => {
  expect(window.localStorage.getItem('myLocalStorageItem')).to.eq(value)
})

// verify that reload retains localStorage value
cy.on('window:before:load', (win) => {      
  // should fire after Cypress clears localStorage
  window.localStorage.setItem('myLocalStorageItem', value)  
}) 
cy.reload()
cy.VerifyCheckBox('A', 'checked')
  • Related