Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress - how to logout from site

Is in Cypress any possibility to log out from page if you are logged in? Or to check if I'm logged?

My problem is that if I'm running tests by one in browser then Cypress always need to log in. But if I start it from cmd it only needs to log in on the first test but at the next one you are already logged in.

// Visit the site
cy.visit(
  "https://zeteodemo.uat.creasoft.cz/login?ReturnUrl=%2fVehicleInsuranceV2%2fCompare%3fOsobniCislo1%3d1%26ProductsFilter%3dAXA-ONLINE"
);

// Enter username
cy.get(".login__username")
  .type("tester")
  .should("have.value", "tester");

// Enter password
cy.get(".login__password")
  .type("1")
  .should("have.value", "1");

// Click the login button
cy.get(".button-login").click();
like image 860
Dominik Skála Avatar asked Oct 14 '25 17:10

Dominik Skála


1 Answers

I've got Cypress tests running for several environments, one of those has issues with the login state. Deleting cookies helps sometimes, but not always. So to keep the tests stable I decided to create an if statement (what in itself isn't a best practice) to go to the known application state as fast as possible.

What I do is using the custom command below in every beforeEach() that could use a login:

Cypress.Commands.add('login', function () {
    cy.get('body').then($body => {
        if ($body.find('.user-profile-name').length === 1) {
            cy.log('Already logged in')
        } else {
            cy.get('.login-button').click()
        }
    })
})

What is does is checking if the browser is already logged in, since .user-profile-name should exist. If it does not exist the browser isn't logged in, so Cypress needs to click the .login-button button.

like image 182
Mr. J. Avatar answered Oct 17 '25 07:10

Mr. J.