Created
November 26, 2019 12:22
-
-
Save adeelibr/273a6450088b9380c4e5915ae97650c4 to your computer and use it in GitHub Desktop.
Persist Login Between Tests In Cypress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
before(() => { | |
cy.clearInfo(); | |
cy.login(); | |
}); | |
after(() => { | |
cy.contains('Logout').click(); | |
cy.contains('Login'); | |
}); | |
beforeEach(() => { | |
cy.log('Update localStore from cache'); | |
cy.setTokenFromCache(); | |
}); | |
afterEach(() => { | |
cy.log('Update localStorage cache'); | |
cy.updateTokenCache(); | |
}); | |
Cypress.Commands.add('login', () => { | |
cy.log('Logging into the dashboard'); | |
cy.visit('/') // Provide the credentials | |
.get("[id='username']") | |
.type(Cypress.env('username')) | |
.get('input[type="password"]') | |
.type(Cypress.env('password')) | |
.get('input[value="Secure login"]') | |
.click(); | |
cy.contains('Logout'); // Verify the login is successful | |
}); | |
/** This is done in order to avoid loggin in again after every test block. **/ | |
let LOCAL_STORAGE_CACHE = {}; | |
Cypress.Commands.add('updateTokenCache', () => { | |
Object.keys(localStorage).forEach(key => { | |
LOCAL_STORAGE_CACHE[key] = localStorage[key]; | |
}); | |
}); | |
Cypress.Commands.add('setTokenFromCache', () => { | |
Object.keys(LOCAL_STORAGE_CACHE).forEach(key => { | |
localStorage.setItem(key, LOCAL_STORAGE_CACHE[key]); | |
}); | |
}); | |
Cypress.Commands.add('clearInfo', () => { | |
localStorage.clear(); | |
LOCAL_STORAGE_CACHE = {}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment