How to log in and log out user, before running tests

Viewed 586

In Cypress I'm trying to test something in a backend. I'm really struggling to control if the user is logged in or not.

I'm trying to automate all testing that i do, when developing features. I spend so much time and effort to control if the user is logged in or not.

I'm looking for a command that does this:

  1. Logout any user (if one is logged in), when starting any test.
  2. A fast way to do something like: cy.loginUser( 'foo@example.org', 'password' )?

Since this will have to run before many of the tests, if would be nice to streamline it.

It's being used on a Laravel / Vue application (hence the CSRF-token).

My current attempt:

Cypress.Commands.add( "loginUser", ( email, password ) => {
  cy.server();
  
  // Source: https://github.com/cypress-io/cypress/issues/413
  sessionStorage.clear();
  cy.clearCookies();
  cy.clearLocalStorage();
  cy.window().then((win) => {
  win.sessionStorage.clear()
  });
  
  cy.visit( Cypress.env( 'baseUrl' ) + "/login");
  
  cy.location().should((loc) => {
    expect(loc.pathname).to.eq('/login')
  });
  
  cy.get("head meta[name=csrf-token]")
    .then((meta) => {
    const csrf = meta[0].content;
  
    cy.request({
      method: 'POST',
      url: '/login',
      body: {
        _token: csrf,
        email: email,
        password: password
      }
    });
  });
  
  cy.visit( Cypress.env( 'baseUrl' ) + "/login");
});

The problems with this:

  • For some wierd reason... Every second time, the user remains logged in from the previous session. But if that happens, then I simply have to run it again, - and then the user is logged out. It's driving me bananas.
  • It's not slow, - but it's not fast either (considering that I do it a bazillion times). So if it could be done faster (with less page loads), then it would be smashing.
1 Answers

Try to use another way to clear localStorage. For example, I'm using these commands to save, restore and clear storage and is working perfect. I'm using these for log in/log out things.

let LOCAL_STORAGE_MEMORY = {};

Cypress.Commands.add("saveLocalStorage", () => {
  Object.keys(localStorage).forEach(key => {
    LOCAL_STORAGE_MEMORY[key] = localStorage[key];
  });
});

Cypress.Commands.add("restoreLocalStorage", () => {
  Object.keys(LOCAL_STORAGE_MEMORY).forEach(key => {
    localStorage.setItem(key, LOCAL_STORAGE_MEMORY[key]);
  });
});

Cypress.Commands.add("clearLocalStorageCache", () => {
  localStorage.clear();
  LOCAL_STORAGE_MEMORY = {};
});
Related