简体   繁体   English

很多时候 cypress 无法访问 /auth 页面并且找不到 id 或 class

[英]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:我正在尝试使用以下代码访问/auth路径并使用 cypress 登录:

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)我的登录页面 url 是 (http://localhost:3000/) 或 (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.自定义命令是非常好的实用程序,但是在内部封装了多个 UI 操作,使得整个测试执行非常缓慢和不稳定,尤其是对于login操作。

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.您的方法完全没有错,但是我建议您通过 API 调用来实现,因此您将拥有稳定而健壮的登录 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);
                },
            });
        });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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