Home > OS >  Check that today's date does not exist in Cypress
Check that today's date does not exist in Cypress

Time:06-22

How can I write a method in Cypress so that first I see what today's date is (but formatted in "June 21" mode) and then the date I find with new Date() , is not visible in my test?

Example of code (not spelled correctly):

const today = new Date(some format);
cy.contains(today).should('not.visible');

Also can i use something like date-fns library?

Thank you

CodePudding user response:

You can do something like this:

const today = new Date()
const month = today.toLocaleString('default', {month: 'long'}) //June
const date = today.getDate() //21
cy.contains(month   ' '   date).should('not.be.visible') //checks 'June 21' is not visible

CodePudding user response:

You'll use the format and pass in MMMM to get the month full name (ie August) along with dd to get the day of the month. Then pass that formatted date into your .contains().

NOTE: you can pass a selector as the first argument in the .contains() for better filtering or it will search the entire page for the date format which may exist.

import { format } from 'date-fns'

var todaysDate = format(new Date(), "MMMM dd") // todays' date 'June 21'

cy.contains(todaysDate) // you can pass a selector as 1st arg for better query
  .should('not.be.visible') // you can sub 'not.exist' to check it does not exist in DOM
  • Related