如何解决在柏树中 - 如何将元素存储在数组中,然后将相同的元素相互比较?
所以我在网页上有一个元素列表,这些元素具有字符串或文本格式的日期。 我想提取它们并将它们分成三个 - dd、mm 和 yyyy 部分。 然后,我必须按此顺序连接它们 - yyyy+mm+dd,以便我始终可以确定 日期是否已排序。
例如,假设我提取的日期列表是:
07/20/2021
07/19/2021
06/23/2021
06/22/2021
05/18/2020
所以我使用 substring() 分割它们,所以它们看起来像:
dd = ["20","19","23","22","18"]
mm = ["07","07","06","05"]
yyyy = ["2021","2021","2020"]
然后我连接它们:
dates = ["20210720","20210719","20210623","20210622","20200518"]
但是,我使用 Cypress 进行自动化;并发布 Cypress 7.4 我想我无法使用 for 循环遍历数组,每当我尝试这样做时:
let dates = cy.get('<locator string>');
for (let i = 0; i < dates.length; i++) {
<Iterate and compare the dates>
}
能够做到这一点会非常有帮助。
但是我做不到。所以,如果有另一种方式,比如使用:
cy.get(<locator string>).then($el)
或
cy.get(<locator string>).each($el)
请告诉我。
解决方法
您可以将 jQuery 元素转换为数组并使用 .map()
来迭代和转换它们(多种选择之一)
cy.get('<locator string>').then($dateEls => {
const dateStrings = [...$dateEls].map(el => el.innerText) // convert els to texts
const isoDates = dateStrings.map(dateString => { // convert format
const [mm,dd,yyyy] = dateString.split('/') // destructure
return `${yyyy}${mm}${dd}`
})
isoDates.sort().reverse() // sort descending
return isoDates
})
.should('deep.eq',["20210720","20210719","20210623","20210622","20200518"])
.should(dates => {
const [maxDate,...otherDates] = dates // destructure list head and tail
otherDates.forEach(date => {
expect(+date).to.be.lt(+maxDate)) // "+" converts to numeric
})
})
如果元素是 <input>
,您将从 el.value
而不是 el.innerText
注意 [...$dateEls]
使用扩展运算符将类数组对象转换为真正的 JavaScript 数组。
我试过这段代码:
static verifySortingByNewest() {
cy.get('<locator-string>').each(($el) => {
var latest = $el.first().text().substring(6,9).concat($el.first().text().substring(0,1)).concat($el.first().text().substring(3,4));
cy.log(latest);
var current = $el.text().substring(6,9).concat($el.text().substring(0,1)).concat($el.text().substring(3,4));
cy.log(current);
expect(Number(current)).to.be.at.most(Number(latest));
});
}
导致以下断言:
鉴于我的元素数组总是由于应用过滤器而降序排序,我如何使 latest 始终指向第一个元素?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。