Cypress - js date picker function

Viewed 329

This function should, besides another things, select next month if the month of the desired date is not the one which is visible in date picker. But when (!dateAttribute.includes(futureMonth)) is true, it thorws error: "selectDayFromCurrent is not defined". This line "cy.contains('Next Month').click()" works fine when I remove "selectDayFromCurrent(day)" bellow it.

selectDayFromCurrent: (day) => {
  let date = new Date()
  date.setDate(date.getDate() + day)
  let futureDay = date.getDate()
  let futureMonth = date.toLocaleString('default', {
    month: 'long'
  })

  cy.log('date: ' + date)
  cy.log('futureDay: ' + futureDay)
  cy.log('futureMonth: ' + futureMonth)


  cy.get('[class="react-datepicker__current-month react-datepicker__current-month--hasYearDropdown react-datepicker__current-month--hasMonthDropdown"]').invoke('text').then(dateAttribute => {
    if (!dateAttribute.includes(futureMonth)) {
      cy.contains('Next Month').click()
      selectDayFromCurrent(day)
    } else {
      cy.get('.react-datepicker__month').find('.react-datepicker__day').not('.react-datepicker__day--disabled').contains(futureDay).click()
    }
  })
},

1 Answers

The colon after the function name indicates you are defining a method on a class, if so it needs to be referred from this

selectDayFromCurrent: (day) => {

  ...        

  cy.get(...).invoke('text').then(dateAttribute => {
    if (!dateAttribute.includes(futureMonth)) {
      cy.contains('Next Month').click()

      this.selectDayFromCurrent(day)

    } else {
      ...
    }
  })
},

Or you can avoid the use of this (which can be problematic) by moving the recursive function inside the method

selectDayFromCurrent: (day) => {

  function selectWithCorrectMonth(day) {
    ...        

    cy.get(...).invoke('text').then(dateAttribute => {
      if (!dateAttribute.includes(futureMonth)) {
        cy.contains('Next Month').click()

        selectWithCorrectMonth(day)

      } else {
        ...
      }
    })
  }

  selectWithCorrectMonth(day)

},
Related