2

I'm creating a Cypress test to my rest call API. Anyways I need to verify a date format, for example, in my JSON Response I have:

"documentDate": "2022-01-28"

So, with that i need to verify the date format not its value. There is a way on Cypress "expect" to verify that? Idk, maybe something like:

expect(documentDate)to.have.format('yyyy-MM-dd');

If anyone can help me, it will be great.

Thanks.

Fody
  • 23,754
  • 3
  • 20
  • 37

3 Answers3

2

You can use a regex for this. You can use the below regex, which has been taken from this StackOverflow thread.

/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/

In your test you can use:

expect(documentDate).to.match(/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/)
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
1

You should us regex to match the format of your date.

\d is regex for matching any digit character (0-9)

{} is quantifier for the preceding token

expect(documentDate).to.match(/\d{4}-\d{2}-\d{2}/)
jjhelguero
  • 2,281
  • 5
  • 13
1

An alternative is to use the dayjs library.

The problem with regex is it only checks characters, not date validity

import dayjs from 'dayjs'

it('checks date string is a valid date', () => {

  const documentDate = "2022-02-29"    // not valid but passes with regex

  const parsed = dayjs(documentDate, 'YYYY-MM-DD')

  // fails with error "expected 2022-03-01 to equal 2022-02-29"
  expect(parsed.format('YYYY-MM-DD')).to.eq(documentDate)  
})
Fody
  • 23,754
  • 3
  • 20
  • 37