Search code examples
automationcypresscypress-cucumber-preprocessorcypress-component-test-runner

How to add days, month and year to the selected date in cypress


Cypress moment not working. Any other solution to add the days, month and year to the current or selected date.

import * as moment from 'moment'

class TicketPage{
   constructor(){}
    visit(){
        cy.visit('');
    }
    clickDate(){
        const field =cy.get('#content > section.container > div > div > div.col-lg-5.mb-4.mb-lg-0 > form > div:nth-child(3) > div > input')
        field.click()
        const targetDate = Cypress.moment()
         .add(1, 'year')
         .add(1, 'month')
         .add(1, 'day')
         .format('MM/DD/YYYY')
        field.type(targetDate);
        field.invoke('attr', 'placeholder').should('contain', 'Select Date')
        return this
    }
 }

Solution

  • Cypress recommends dayjs as a replacement for moment.

    The syntax looks pretty much the same:

    import dayjs from 'dayjs'
    
    const targetDate = dayjs()
      .add(1, 'year')
      .add(1, 'month')
      .add(1, 'day')
      .format('MM/DD/YYYY')