Codr
Codr

Reputation: 57

How to test in cypress that one date is 6 months earlier than another

I have an svg graph I'm testing and on the x axis it has dynamic dates, for the purpose of this example lets say earlyDate is 'Feb 22' and LaterDate is 'Aug 22'.

I'm able to get the values from each element in the graph and store them in variables but I'm at a loss as to how I check that the earlyDate is always 6months before the laterDate in cypress. So far this is what I have:

//To get the earlyDateValue
cy.get("laterDateSelector").invoke('text').as('val');
  cy.get('@val').then((val) => {
   let laterDate = val;
//Assertion, this is where I'm stuck
cy.get('earlyDateSelector').should('equal', 'Need this part to be equal: laterDate minus 6 months in the format MMM yy');

Upvotes: 1

Views: 613

Answers (1)

TesterDick
TesterDick

Reputation: 10545

Using the dayjs package it's fairly easy.

The date strings you have will parse directly, then do subtraction on the $M properties.

import dayjs from 'dayjs';

it('checks 6 months between dates', () => {
  
  cy.get("earlyDateSelector").invoke('text').then(earlyDate => {       // 'Feb 22'
    cy.get("laterDateSelector").invoke('text').should(laterDate => {     // 'Aug 22'

      const early = dayjs(`01 ${earlyDate}`)  // '01 Feb 22'
      const later = dayjs(`01 ${laterDate}`)  // '01 Aug 22'

      expect(later.$M - early.$M).to.eq(6)

      // or, better for difference across years

      expect(end.diff(start, 'M')).to.eq(6)

    })
  })
})

Upvotes: 1

Related Questions