Cholis
Cholis

Reputation: 105

How to assert today's date or older in Cypress

I am trying to write a function in Cypress, where it loops through all the columns for my start date (#EventStart) and makes sure that the start dates are today's current date or older. So for instance, I need this test to make sure that it is confirming that all the dates listed are either today's date (April 4) or earlier (April 3, 2, 1, etc, etc). So far I can get it to confirm today's date, but how can I add to the function so that it also looks for the days prior to today? Also, the way it is written, it is getting me GMT Time, how can I get it to display CST?

EDIT: This is how the date displays: April 4, 2022, 1:00pm

  public assertOldDate () {
    cy.get("#EventStart).each((el) => {
     let oldDate = new Date();
      oldDate.setDate(oldDate.getDate())
      cy.get("el").should("equal", oldDate);
    }
  }

Upvotes: 0

Views: 4393

Answers (1)

Fody
Fody

Reputation: 31904

Using dayjs to parse the element text,

import dayjs from 'dayjs'

const today = dayjs()

cy.get('[id*="EventStart"]')
  .each($eventStart => {

    const dateText = $eventStart.text()

    Cypress.log({message: `Testing ${dateText}`})               // log as per web page
    const formatted = dateText.split(', ').slice(0,2).join(' ') // remove commas & time 
    const date = dayjs(formatted, 'MMMM DD YYYY')               // parse the text

    expect(date <= today).to.eq(true)
  })

Note, changed id selector to [id*="EventStart"] as id's are expected to bu unique. Using #EventStart seems to block the iteration.

Upvotes: 4

Related Questions