How to iterate months in cypress?

53 views Asked by At

I need to learn how to go from June to February with cypress, clicking month by month. My idea is to obtain the value of the month and if it is not the month February, continue clicking the next button

enter image description here

enter image description here

I was thinking of applying a conditional but it didn't work for me. If someone can fix the code or help me with any ideas, that would be fantastic.

it('Month iterate- conditional assertion', () => {

  let searchMonth = 'february'
  let monthLabel = '.Grid_header__yAoy_ > :nth-child(2)'
  cy.visit('/')
  cy.get('.Grid_header__yAoy_ > :nth-child(2)')
      .then(($el) => {
          monthLabel = $el.length
      })
      .each(($el) => {
          cy.log($el.text())
                  if ($el.text() === searchMonth) {
                      cy.log($el.text() === searchMonth)
                  } else {
                    cy.get('.Grid_header__yAoy_ > :nth-child(3)').click()
                  }
              })
})

I can advance 1 month

1

There are 1 answers

0
Lola Ichingbola On BEST ANSWER

Don't use conditional expressions in your test, it will make the test much more complicated and likely create bugs.

Instead, make the test data definitive.

Remember that an action like click() will probably make the page refresh, so you can end up with a flaky test because queries made earlier are no longer valid.

const now = new Date(2023, 6, 10) // pick a fixed starting date
cy.clock(now)
cy.visit('/')

cy.get('.Grid_header__yAoy_ > :nth-child(2)')
  .then($month => $month.text().trim().toLowerCase())  // convert text exactly
  .should('eq', 'june')

cy.get('.Grid_header__yAoy_ > :nth-child(3)').click()

cy.get('.Grid_header__yAoy_ > :nth-child(2)')
  .then($month => $month.text().trim().toLowerCase())  
  .should('eq', 'may')

cy.get('.Grid_header__yAoy_ > :nth-child(3)').click()

cy.get('.Grid_header__yAoy_ > :nth-child(2)')
  .then($month => $month.text().trim().toLowerCase())  
  .should('eq', 'april')

cy.get('.Grid_header__yAoy_ > :nth-child(3)').click()

cy.get('.Grid_header__yAoy_ > :nth-child(2)')
  .then($month => $month.text().trim().toLowerCase())  
  .should('eq', 'march')

cy.get('.Grid_header__yAoy_ > :nth-child(3)').click()

cy.get('.Grid_header__yAoy_ > :nth-child(2)')
  .then($month => $month.text().trim().toLowerCase())  
  .should('eq', 'february')

You probably don't like all that repetition, but starting from a working test you can refactor

const months = ['june', 'may', 'april', 'march', 'february']

const now = new Date(2023, 6, 10) // pick a fixed starting date
cy.clock(now)
cy.visit('/')

months.forEach((month, index) => {
  cy.get('.Grid_header__yAoy_ > :nth-child(2)')
    .then($month => $month.text().trim().toLowerCase())  
    .should('eq', months[index])

  cy.get('.Grid_header__yAoy_ > :nth-child(3)').click()
})