Thierry Templier
Thierry Templier

Reputation: 202346

Select a date with Material Datepicker with Cypress

I'm implementing some tests using Cypress for an application implemented with Angular and Angular Material.

For some of my screens, I have some forms with date pickers and I want to fill these fields in my tests using the picker not using the type method of Cypress.

So I need to make things generic:

So my questions are:

Thanks very much for your help, Thierry

Upvotes: 0

Views: 3607

Answers (1)

user14903560
user14903560

Reputation:

Select the correct month (so I have to iterate over months until the correct month is found)

This sounds something like (pseudo code)

while (cy.contains('#mat-calendar-button-0', targetMonth)) {
  cy.get('button.mat-calendar-next-button').click()
}

but it won't work because Cypress commands are queued and run async to the while loop. (also the return is not useable in this way).

There are many questions asking for conditional testing, most answers end up being in-elegant branching code that does what Cypress terms 'backflips' to set a closure variable that controls the while loop.

But if you know that the page starts with (say) month 'Jan' and you want to set month 'Jun' you can use a simpler for loop which does not rely on page testing to finish

// advance 5 months
for (let i = 0; i < 5; i++) {                        // queues up 5 clicks
  cy.get('button.mat-calendar-next-button').click()
} 

If you really must use conditional testing (say the next button was flaky and did not always respond to click), you would use a synchronous jQuery expression to control the loop, something like

while (!Cypress.$(`#mat-calendar-button-0:contains(${targetMonth}).length) {
  cy.get('button.mat-calendar-next-button').click()
}

but the problem is you loose Cypress' auto-retry that's built in to (most) commands. Any async code happening after clicks, even animation, can make the test flaky.

Upvotes: 1

Related Questions