Search code examples
javascriptcypressdayjs

How to find the time difference with dayjs in cypress?


I'm trying to find the time taken for an element to load using this code but doesn't work.

Expected Result: Total time taken is 90 seconds(or in milliseconds)

const start = cy.log(dayjs.format("HH:mm.ss.SSS));
const end = cy.log(dayjs.format("HH:mm.ss.SSS));

const diff = dayjs(end).unix() - dayjs(start).unix();
const timetaken = dayjs.utc(diff).format("HH.mm.ss.SSS");

cy.log(timetaken);

Solution

  • It gets a bit tricky because Cypress runs things in a command queue, you need to run (most) dayjs commands in .then() callbacks.

    Here's a simple example

    import dayjs from 'dayjs'
    
    const duration = require('dayjs/plugin/duration')
    dayjs.extend(duration)
    
    it('times loading a site and selecting an element', () => {
    
      const start = dayjs();
      let end;
    
      cy.visit('http://example.com')
      cy.get('h1').then(() => {    
        // ensure end is set only after get command finishes
        // by using a .then()
    
        end = dayjs();   
        cy.log(`start: ${start.format("HH:mm.ss.SSS")}`)
        cy.log(`end: ${end.format("HH:mm.ss.SSS")}`)
        cy.log(`diff: ${dayjs.duration(end.diff(start)).$ms} ms` )
      })
    })
    

    If you want to do some more testing steps before diffing, you can use Cypress aliases to keep a hold of the start and end.

    import dayjs from 'dayjs'
    
    const duration = require('dayjs/plugin/duration')
    dayjs.extend(duration)
    
    it('times loading a site using aliases', () => {
    
      cy.wrap(dayjs()).as('start')
    
      cy.visit('http://example.com')
      cy.get('h1').then(() => {
        cy.wrap(dayjs()).as('end');    // must wrap "end" inside a .then()!
      })
    
      // other test stuff here
    
      cy.get('@start').then(start => {
        cy.get('@end').then(end => {
          cy.log(`start: ${start.format("HH:mm.ss.SSS")}`)
          cy.log(`end: ${end.format("HH:mm.ss.SSS")}`)
          cy.log(`diff: ${dayjs.duration(end.diff(start)).$ms} ms` )
        })
      })
    
    })