I have a command where I can enter a specific date for start date, please see below a part of the command I am using.
and when I am calling it in the test I need to enter a dynamic date like today <=(+30 days)
cy.create123((new Date().getDate() - 1), '2023-08-07')
ofc it did not work, but I have no idea how can I do it. How I can setup to cy.command to get always today-1 as startDate!
My issue is to make the dynamic enter date to work on Cypress.Commands()
Install dayjs and use
const startDate = dayjs().add(-1, 'day').format('YYYY-MM-DD')
cy.create123(startDate, '2023-08-07')
The Custom Command and the cy.request()
inside it are expecting the date as a string type.
Your calculated dynamic date (new Date().getDate() - 1)
is giving you a number type.
But .toISOString()
only works on Date types, not number types.
So after doing math on the Date(), you get a number which must be converted into a Date and then into a string.
const today = new Date()
const yesterday = new Date(today.setDate(today.getDate() -1))
const startDate = yesterday.toISOString()
But even that's not the end of the problems, because the timezone might give you invalid dates.
I recommend using dayjs
as shown above.