Stacey
Stacey

Reputation: 333

Set datepicker for one year from today in Cypress test

I am creating an acceptance test in Cypress that will run regularly, and I need that it enters the date from the datepicker (React, if it is important) as 1 year 1 month and 1 day from the day of creating the object (article). E.g. Today is April 22, 2020, and I want to get May 23, 2021 in the article created today, and tomorrow it would give the value of May 24, 2021 etc. Could anyone share any ideas of setting this up? I honestly googled and I have no ideas myself because I'm quite new to Cypress and feel more or less confident only in pretty straightforward things. :)

Upvotes: 3

Views: 21942

Answers (2)

ekrem
ekrem

Reputation: 26

This method was deprecated. You can use this method;

//click the date picker
    cy.get('#datepicker').click();
    //choose previous month
    cy.contains('Prev').click();
    //choose next month 
    cy.contains('Next').click();
    //choose date 24
    cy.contains('24').click();

Upvotes: 1

Richard Matsen
Richard Matsen

Reputation: 23463

I'd guess that most date pickers will have an input element where the date can be typed.

Presuming the app uses a library date picker (so you don't need to test the picking of the date via button clicks), you can target that element and use the Cypress .type() command to enter the future date.

For example, the Material UI date picker docs has this input element

<input aria-invalid="false" 
  id="date-picker-inline" 
  type="text" 
  class="MuiInputBase-input MuiInput-input MuiInputBase-inputAdornedEnd" 
  value="08/18/2014">

so the steps would be something like

cy.visit('https://material-ui.com/components/pickers');

const targetDate = Cypress.moment()
  .add(1, 'year')
  .add(1, 'month')
  .add(1, 'day')
  .format('MM/DD/YYYY')   // adjust format to suit the apps requirements

cy.get('input[id="date-picker-inline"]')
  .clear()
  .type(`${targetDate}{enter}`)  // presume you need the enter key to trigger an event 

Ref: Cypress.moment

Upvotes: 3

Related Questions