Home > Net >  Cypress Testing - Expect a date format
Cypress Testing - Expect a date format

Time:03-12

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.

CodePudding user response:

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])$/)

CodePudding user response:

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}/)
  • Related