Кипарис: Нужна помощь в динамическом размещении элемента

#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])
})
 

Комментарии:

1. У вас есть массив где — то в вашем тестовом сценарии — finYear[0] ?

2. Да, его конечный год[0] является массивом

Ответ №1:

Если это всегда 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))

  })
})
 

Комментарии:

1. Спасибо, я остановлюсь на первом решении, потому что заголовок распределен по нескольким массивам

Ответ №2:

Вы можете использовать each() непосредственно, чтобы проверить внутренний текст всех элементов по одному —

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