Reputation: 1
so I have a simple code like :
it('login', function(){
cy.visit('/login')
cy.get('[formcontrolname="username"]').type(Cypress.env('myuname'))
cy.get('[formcontrolname="password"]').type(Cypress.env('mypwd'))
cy.get('[type="submit"').should('be.enabled').click()
cy.url().should('include','/dashboard')
})
after this the page is logged in as expected but right after instead of showing the user in the dashboard it is logged out.
in the logs of the cypress I only get 3 "new url" with
Before going on vacation for 3 weeks this worked but since coming back for some reason it does not. There was nothing changed in the code of the webpage.
Trying this manually in chrome and firefox it works as expected and the user stays logged in. Watching the console while executing the test I noticed that the token is present at the login moment but after that it gets deleted for some reason.
Except the workaround presented here: https://github.com/cypress-io/cypress/issues/461 is there another way to make this work as expected?
I need to test different views depending on the user role so I need to change the role with a third user and then log in but this cannot be done if the user is logged out constantly.
I also cannot save a general token since the user role is changing so also the token value is changing.
Thanks in advance !
P.S. Oh and another unfortunate thing: it does not happen always, happens for about 80% of the times I run the same test :(
Upvotes: 0
Views: 585
Reputation: 672
After every it
instance, Cypress clears all cookies before the next instance. So it's to be expected that you are logged out. Sometimes Cypress gives you the illusion to still be logged in but that it just because the page is still loaded in the browser.
The simplest solution that worked for me was adding before the first it
beforeEach(function () {
cy.preserveAllCookiesOnce()
})
Then put this in your command.js
Cypress.Commands.add('preserveAllCookiesOnce', () => {
Cypress.Cookies.defaults({
preserve: (cookie) => {
return true;
}
})
})
Alternatively you can add this to your index.js
in your support
folder:
afterEach(() => {
//Code to Handle the Sesssions in cypress.
//Keep the Session alive when you jump to another test
let str = [];
cy.getCookies().then((cook) => {
cy.log(cook);
for (let l = 0; l < cook.length; l++) {
if (cook.length > 0 && l == 0) {
str[l] = cook[l].name;
Cypress.Cookies.preserveOnce(str[l]);
} else if (cook.length > 1 && l > 1) {
str[l] = cook[l].name;
Cypress.Cookies.preserveOnce(str[l]);
}
}
})
});
Upvotes: 0