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:
- Logout any user (if one is logged in), when starting any test.
- 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.