Cypress 对调用的文本返回未定义

tes*_*way 0 cypress

我试图从元素中提取文本,以便稍后确保在某些操作后它存在或不存在。Cypress 可以很好地提取文本,但undefined在断言期间将其返回,从而产生失败或误报结果。这是代码:

cy.get('.peeking-carousel__track')
            .children()
            .first()
            .find('.peeking-carousel__title')
            .invoke('text')
            .as('firstSlide')

        cy.get('@firstSlide')
            .then(firstSlide => {
                cy.log(firstSlide); //logs the text correctly
                cy.contains(firstSlide).should('be.visible'); //fails because can't locate it, even though it's displayed
               
                cy.get('.peeking-carousel')
                    .find('.icon-arrow-forward')
                    .should('have.css', 'cursor', 'pointer')
                    .click();
                cy.contains(firstSlide).should('not.exist'); //passes but refers to firstSlide as undefined
                
            })
Run Code Online (Sandbox Code Playgroud)

我一直在挖掘类似的问题,但找不到适合我的解决方案。

小智 6

我认为问题出在文本值别名上。如果您为元素添加别名,Cypress 将重试查询该元素。

轮播上的元素通常是隐藏的而不是被破坏的,所以这.should('not.exist')不是最好的测试。

cy.get('.peeking-carousel__track')
  .children()
  .first()
  .as('firstSlide')
  .should('be.visible')

cy.get('.peeking-carousel')
  .find('.icon-arrow-forward')
  .should('have.css', 'cursor', 'pointer')
  .click()

cy.get('@firstSlide')
  .should('not.be.visible')
Run Code Online (Sandbox Code Playgroud)