cypress - 将一个日期值与其他日期进行比较并在 cypress 中执行条件操作
问题描述
我正在尝试将一个日期值(即基值)与页面上的所有其他日期值进行比较,并且根据这些天之间的差异,我想执行其他命令。
那么,在上面的 UI 中,基值为2021 年 7 月 11 日(第一个列表中的出发日期),其他日期值为2021 年 7 月 12 日、2021 年 7 月 20 日、2021 年 7 月 27 日、2021 年 8 月 3 日等(到达日期从 2 日开始)往下列出)。
现在,我必须删除基值和特定列表之间的日期差异小于 15 天的所有列表。在这种情况下,必须删除2021 年 7 月 27 日、2021年 7 月 20 日和 2021年 7 月 27 日、2021 年 8 月 3 日等的所有列表,如下图所示。
到目前为止,我已经捕获了基值的值并提出了将其与另一个日期值进行比较的逻辑,但我不确定如何将第二个和更多的日期值保存到一个变量中以便比较基值。
{
cy.get("[data-test='departureTime']")
.eq(0)
.then((date) => {
const depDate_FirstPort = new Date(date.text());
cy.log(depDate_FirstPort.toISOString()); //2021-07-11T19:00:00.000Z
// const arrDate_SecondPort = new Date(cy.get('[data-test="arrivalTime"]').eq(1).invoke('text'));
// Since the above approach does not work, hard coding now.
const arrDate_SecondPort = new Date("22 Jul 2021 12:01")
cy.log(arrDate_SecondPort.toISOString()); //2021-07-22T10:01:00.000Z
cy.getDifferenceBetweenDates(depDate_FirstPort,arrDate_SecondPort).then((dif)=>{
if(dif < 16) {
cy.log("delete the port entry");
//do something
}
});
});
}
赛普拉斯命令:
Cypress.Commands.add("getDifferenceBetweenDates", (Date1, Date2) => {
var diff_times = Math.abs(Date1.getTime() - Date2.getTime());
var diff_days = Math.ceil(diff_times / (1000 * 3600 * 24));
cy.log(diff_days) //11
})
此外,很想知道根据上述条件迭代所有列表的可能方法属于“待删除列表”(2021 年 7 月 12 日,2021 年 7 月 20 日)。
解决方案
您拥有的迭代方法是可以的,但是您需要重复第一个日期的代码才能获得后续日期。
所以,这一点,但改变了索引
cy.get("[data-test='departureTime']")
.eq(0) // 1,2,3 etc
.then((date) => {
另一种方法是过滤整个集合,
const dayjs = require('dayjs') // replaces Cypress.moment
// first install with
// yarn add -D dayjs
it('finds the skipped ports', () => {
// helper func with format specific to this website
const toDate = (el) => dayjs(el.innerText, 'D MMM YYYY HH:mm')
cy.get("[data-test='departureTime']")
.then($departures => {
const departures = [...$departures] // convert jQuery object to an array
const first = toDate(departures[0]);
const cutoff = first.add(15, 'day')
const nextPorts = departures.slice(1) // all but the first
const skipPorts = nextPorts.filter(port => toDate(port).isBefore(cutoff))
expect(skipPorts.length).to.eq(2)
expect(skipPorts[0].innerText).to.eq('12 Jul 2021 14:02')
expect(skipPorts[1].innerText).to.eq('21 Jul 2021 04:00')
})
})
我不清楚您的目标,但是如果您要从页面中实际删除skipPorts 而不仅仅是测试它们,您应该警惕DOM 列表在您这样做时发生变化。
从您最近查询的列表中删除cy.get("[data-test='departureTime']")
会导致内部主题变为无效,并且您可能会收到“与 DOM 分离”错误或删除错误的项目。
推荐阅读
- git - 在不提交新分支的情况下合并 git repo 的本地更改
- customization - 根据当前文件夹更改 Powerlevel9k 段
- asp.net - 将媒体文件从一个文件夹复制到另一个文件夹,但重命名文件
- java - 具有多个客户端的中央身份验证服务器使用资源所有者密码凭据 oauth 流
- reactjs - 没有'Access-Control-Allow-Origin' Symfony 3 和 React
- javascript - 将使用 axios 获取的 json 数据拆分为一个可点击的列表项,该列表项重定向到页面
- c++ - 处理 std::map
和 std::map 以类似的方式 - python - Scapy DNS 请求
- java - 错误:java.util.Vector 无法转换为 org.ksoap2.serialization.SoapObject
- oracle11g - Coldfusion 将 href URL 链接插入 DB Oracle