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])
})
解决方案
如果总是第二个标题元素不存在,则可以调整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])
}
})
})
如果您只想回答问题Are all headers in 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))
})
})
推荐阅读
- c - GPS + IMU 融合过滤器
- regex - Match end of line if line contains specific text
- sql - Chaining multiple queries in SQL
- c++ - QML pointer handlers and handling grab changes
- kotlin - Kotlin multiplatform. Ktor download big file and save to local file
- google-forms - How to set event listeners to Google Forms in script
- asp.net-mvc - How to create memory cache with async generator
- visual-studio-code - 由于未知问题,Visual Studio Code 颜色主题在启动时重置
- powershell - 在 powershell 中无法识别 get-windowsfeatures
- javascript - 当我有多个使用效果时,将调用使用效果清理功能