Reputation: 81
I am trying to visit /auth
path and login in with cypress using the following code:
Cypress.Commands.add('login', (email, password) => {
cy.get('.auth').find('.login').should(($login) => {
expect($login).to.contain('auth.welcome')
})
cy.get('[name="email"]').type(email);
cy.get('[name="password"]').type(password);
cy.get('button.login')
.click();
})
But Cypress fails with the following error message:
AssertionError: Timed out retrying: Expected to find element: `.auth`, but never found it.
Sometimes the code works and sometimes it fails.
my login page url is (http://localhost:3000/) or (http://localhost:3000/auth)
Upvotes: 1
Views: 905
Reputation: 625
Custom commands are very good utilities, but encapsulating multiple UI actions inside, make the overall test execution very slow and flaky especially for login
actions.
It is not wrong at all your approach, however I would suggest doing it via API calls, so in result you will have a stable and robust login function.
Cypress.Commands.add('login', (username, password) => {
return cy
.request('POST', `${<YOUR_API_URL>}/auth`, {
username,
password,
})
.its('body.token')
.then(token => {
cy.visit(`/`, {
onBeforeLoad(win) {
win.sessionStorage.setItem('token', token);
},
});
});
});
Upvotes: 3
Reputation: 1110
this command will wait the element:
cy.get('.auth').should('be.visible');
Add this command before interacting with it.
Upvotes: 3