Skip to content

Instantly share code, notes, and snippets.

@adeelibr
Created November 26, 2019 12:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adeelibr/273a6450088b9380c4e5915ae97650c4 to your computer and use it in GitHub Desktop.
Save adeelibr/273a6450088b9380c4e5915ae97650c4 to your computer and use it in GitHub Desktop.
Persist Login Between Tests In Cypress
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