Cypress: How to test good morning/afternoon/evening based on the time the test is run in cypress

Viewed 74

How do I best test a greeting message that says Good Morning/Afternoon/Evening based on the time the test is run. I'm new to cypress, I've searched for this but could not find examples for this. Is there a better approach than what I'm done?

    it("verify correct greeting message is displayed", () => {
        const now = new Date(Date.now())
        const hours = now.getHours()

        cy.wrap(hours).then(($time) => {
            if ($time < 12)
                cy.findByTestId("greeting").should("have.text", "Good Morning")
            else if ($time >= 12 && $time < 17)
                cy.findByTestId("greeting").should("have.text", "Good Afternoon")
            else
                cy.findByTestId("greeting").should("have.text", "Good Evening")
        })
    })
2 Answers

You can be more concise with a mapping function,

const timeOfDay = () => {
  const hours = new Date().getHours()
  return hours < 12 ? 'Morning' :
         hours < 17 ? 'Afternoon' :
         'Evening'
}

cy.findByTestId('greeting')
  .its('text')
  .should('eq', `Good ${timeOfDay()}`)

I think your test looks good. You can further use custom commands as well to hide the if-else logic from the main test. Or, you can also re-arrange the test a bit like this.

it('verify correct greeting message is displayed', () => {

  const hours = new Date(Date.now()).getHours()

  cy.findByTestId('greeting').then(($ele) => {
    if (hours < 12) cy.wrap($ele).should('have.text', 'Good Morning')
    else if (hours >= 12 && hours < 17)
      cy.wrap($ele).should('have.text', 'Good Afternoon')
    else cy.wrap($ele).should('have.text', 'Good Evening')
  })
})
Related