CypressDog
CypressDog

Reputation: 249

Cypress: Add option to allow LocalStorage

The following facts:

  1. page 'X' Open -> cy.visit('/x');
  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!

Upvotes: 0

Views: 2266

Answers (5)

CypressDog
CypressDog

Reputation: 249

I have found a second solution for my problem. I added at the beginning of my test case (in describe, bevor it) this:

beforeEach(() => {
        cy.restoreLocalStorage().then(() => {
            cy.log('Storage restored');
        })
    });

    afterEach(() => {
        cy.saveLocalStorage().then(() => {
            cy.log('Storage saved');
        })
    });

I hope I can help you with it! Let me know it!

Upvotes: 0

CypressDog
CypressDog

Reputation: 249

Thank you all!

I have found the best solution for me.

First I have installed the cypress-localstorage-commands Then:

it('open Website and check Checkbox A', () => {
    ... cy.saveLocalStorage();
});
                                                                  
it('open Website and verify Checkbox A', () => {
    cy.restoreLocalStorage(); ... 
});

Upvotes: 0

CypressDog
CypressDog

Reputation: 249

Thank you very much for your answers. I am still having a bit of trouble entering the correct values for 'setItem'.

A checked checkbox contains the class 'ag-checked'. Could this be the value I need to include as information in 'setItem'?

I would have expected the necessary data to be automatically read from the cache.

Upvotes: 0

Fody
Fody

Reputation: 31862

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')

Upvotes: 1

agoff
agoff

Reputation: 7125

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.

Upvotes: 0

Related Questions