Home > Software engineering >  CYPRESS: How to add one month to my current date with consideration to months like February(28 days)
CYPRESS: How to add one month to my current date with consideration to months like February(28 days)

Time:04-01

I have this cypress test where Im checking for a correct billing date. Our website has monthly subscriptions and it works as follows: If you start your subscription on January 31st, your next billing date will automatically be on the 1st of March since February has only 28 days. Same if you start your subscription on the 31st of March, then your next billing date will be on the first of 1st of May since there is no 31st in April and it automatically changes to the first day of the next month. Starting on other normal dates like the 15th will always be the same date (15th) of the next month etc..

My issue is when testing this with cypress, i always get the last day of the next month. For example if i test that Im gonna start my subscription on the 31st of March, my test will have 30th of April as an expected result, which is not correct since i want the expected result of my test to be 1st of May.

I am using this function but i cant seem to make it work properly since there are many differences in the months.

export const getBillingDate = (todayDate: string, months: number) => {
  const date1 = new Date(todayDate)
  const date2 = new Date(todayDate)
  date1.setDate(1)
  const daysInNextMonth = getDaysInMonth(addMonths(date1, months))
  date2.setDate(Math.min(date2.getDate(), daysInNextMonth))
  return format(addMonths(date2, months), 'MMMM do, yyyy')
}

I would really appreciate anyone's help with this since i am new to Cypress and testing in general. (Sorry english is not my first language)

CodePudding user response:

Date log

In case you want to format it like DD/MM/YYYY, you have to use .format('DD/MM/YYYY'). Or if you want to format the date to something else, you can also check out the list of format options available.

  • Related