Skip to content

Instantly share code, notes, and snippets.

@jennifer-shehane
Last active March 9, 2020 04:46
Show Gist options
  • Save jennifer-shehane/0afbd820803c30b9333b5c7404af9ce1 to your computer and use it in GitHub Desktop.
Save jennifer-shehane/0afbd820803c30b9333b5c7404af9ce1 to your computer and use it in GitHub Desktop.
restoring local storage over tests
let LOCAL_STORAGE_MEMORY = {};
Cypress.Commands.add("saveLocalStorage", () => {
cy.log("saveLocalStorage");
Object.keys(localStorage).forEach(key => {
LOCAL_STORAGE_MEMORY[key] = localStorage[key];
console.log('localStorage')
cy.log("saving[" + key + "]");
});
});
Cypress.Commands.add("restoreLocalStorage", () => {
cy.log("restoreLocalStorage");
Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => {
localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]);
console.log('localStorage')
cy.log("restoring[" + key + "]");
});
});
describe('Sessions', () => {
beforeEach(() => {
cy.restoreLocalStorage();
});
afterEach(() => {
cy.saveLocalStorage();
});
before(() => {
cy.visit('https://example.cypress.io/commands/local-storage')
cy.get('.ls-btn').click().should(() => {
expect(localStorage.getItem('prop1')).to.eq('red')
expect(localStorage.getItem('prop2')).to.eq('blue')
expect(localStorage.getItem('prop3')).to.eq('magenta')
})
});
it('should visit page', () => {
cy.visit('https://docs.cypress.io')
cy.wrap(localStorage.getItem('prop1')).should('eq', 'red')
cy.wrap(localStorage.getItem('prop2')).should('eq', 'blue')
cy.wrap(localStorage.getItem('prop3')).should('eq', 'magenta')
});
it('should visit second page', () => {
cy.visit('https://www.cypress.io')
cy.wrap(localStorage.getItem('prop1')).should('eq', 'red')
cy.wrap(localStorage.getItem('prop2')).should('eq', 'blue')
cy.wrap(localStorage.getItem('prop3')).should('eq', 'magenta')
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment