Search code examples
javascriptdatetimecypressdayjscypress-dayjs

Cypress, javascript: dayjs does not return current date correctly


I am coding cypress tests. I use cypress v10.3.0.

I am getting a wrong date when I use dayjs function for the second time.

var dayjs = require('dayjs')
cy.log(dayjs(new Date()).format('DD/MM/YYYY HH:mm:ss'))
cy.wait(5000)
cy.log(dayjs(new Date()).format('DD/MM/YYYY HH:mm:ss'))

Output picture:

output picture

output text (same text as in the picture):

  1. log 13/07/2022 10:20:24
  2. wait 5000
  3. log 13/07/2022 10:20:24

First log is ok, but second log should be: 13/07/2022 10:25:24

Why is the first and second log the same? Thank you for your help


Solution

  • That is the expected output.

    Reason is, cy.log() (both lines) takes it's value before the commands run, before the cy.wait() happens.

    You can change it to this

    cy.log(dayjs(new Date()).format('DD/MM/YYYY HH:mm:ss'))
    cy.wait(5000)
    cy.then(() => {
      cy.log(dayjs(new Date()).format('DD/MM/YYYY HH:mm:ss'))  //wait to take value
    })
    

    to see 5 seconds (approx) difference.

    The cy.then() wrapper delays setting up the log command, and delays evaluating dayjs(new Date()).format('DD/MM/YYYY HH:mm:ss') until after the cy.wait() has run.