简体   繁体   中英

Many times cypress can't visit /auth page and can't find id or class

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)

this command will wait the element:

cy.get('.auth').should('be.visible');

Add this command before interacting with it.

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);
                },
            });
        });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM