Cypress:需要帮助动态定位元素

时间:2021-07-26 16:58:21

标签: cypress

我有以下代码, 假设第二个元素不存在,我的脚本将失败。有没有办法动态更改 .eq 值?

即如果第二个断言被注释,那么第三个语句应该采用 .eq(3) 而不是 .eq(5)

cy.get('[data-testid=financials-overview-balance-sheet-card]').within(() => {
        cy.get('table[type="financial"] thead th').eq(1).should("have.text",finYear[0])
        cy.get('table[type="financial"] thead th').eq(3).should("have.text",finYear[1])
        cy.get('table[type="financial"] thead th').eq(5).should("have.text",finYear[2])
        cy.get('table[type="financial"] thead th').eq(7).should("have.text",finYear[3])
        cy.get('table[type="financial"] thead th').eq(9).should("have.text",finYear[4])
})
cy.get('[data-testid=financials-overview-balance-sheet-card]').within(() => {
        cy.get('table[type="financial"] thead th').eq(1).should("have.text",finYear[0])
       // cy.get('table[type="financial"] thead th').eq(3).should("have.text",finYear[1])
        cy.get('table[type="financial"] thead th').eq(5).should("have.text",finYear[2])
        cy.get('table[type="financial"] thead th').eq(7).should("have.text",finYear[3])
        cy.get('table[type="financial"] thead th').eq(9).should("have.text",finYear[4])
})

2 个答案:

答案 0 :(得分:0)

可以直接用一个each()来一一检查所有元素的内部文字-

 cy.get('table[type="financial"] thead th').each(($ele, index) => {
    expect($ele).to.have.text(finYear[index])
})

答案 1 :(得分:0)

如果总是第 2 个标题元素不存在,您可以调整 finYear 数组

cy.get('[data-testid=financials-overview-balance-sheet-card]').within(() => {

  cy.get('table[type="financial"] th').its('length').then(th_count => {

    const expected = [...finYear];
    if (th_count < finYear.length *2) {
      expected.splice(1, 1);     // remove the 2nd answer
    } 

    for (let i = 0; i < expected.length; i++) {
      cy.get('table[type="financial"] th').eq((i*2)+1)
        .should("have.text", expected[i])
    }
  })
})

如果您只想回答所有标题都在 finYear

使用finYear.includes()

cy.get('[data-testid=financials-overview-balance-sheet-card]').within(() => {

  cy.get('table[type="financial"] th').each(($th, index) => {
    
    if (index % 2 === 0) return;  // ignore even columns

    cy.wrap($th).invoke('text')
      .should(headerText => finYear.includes(headerText))

  })
})