首页 > 解决方案 > 将一个日期值与其他日期进行比较并在 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 日)。

标签: cypress

解决方案


您拥有的迭代方法是可以的,但是您需要重复第一个日期的代码才能获得后续日期。

所以,这一点,但改变了索引

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 分离”错误或删除错误的项目。


推荐阅读