skip to Main Content

I have a field that has a date and i want to check the value in it is the current date in the format YYYY-MM-DD. How can i do this. Thanks in advance for any help given

I tried this

cy.window().then((win) => {
         const newDate = new Date(win.Date());
cy.get('#datefrom').should('be.visible').and('have.value', newDate)

but am getting this error

Timed out retrying after 4000ms: expected ‘<input#datefrom.form-control>’ to have value Wed, 05 Apr 2023 15:50:37 GMT, but the value was ‘2023-04-05’

Question – How can i change the format of newDate show it just shows the value as YYYY-MM-DD

2

Answers


  1. Convert to an ISO string and take just the first part

    const currentDateYyyyMmDd = new Date().toISOString().slice(0,10)
    console.log(currentDateYyyyMmDd)
    

    Whose output is currently this:

    2023-04-05
    

    In your case, try this:

    cy.window().then((win) => {
             const newDate = new Date().toISOString().slice(0,10));
    cy.get('#datefrom').should('be.visible').and('have.value', newDate)
    
    Login or Signup to reply.
  2. Tests should be conducted at a fixed date to avoid variations due to current date.

    The example to follow is here Specify a now timestamp

    const now = new Date(2021, 3, 14) // month is 0-indexed
    
    cy.clock(now)
    cy.visit('/index.html')
    cy.get('#datefrom').should('have.value', '2021-04-14')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search