sbmoschw
sbmoschw

Reputation: 15

Compare two dates in cypress

How can I compare two dates in Cypress without them beeing modified?

             let today = new Date();
let dateDisplayed = "22.07.2022".split('.');
    let dateToCompare = new Date(
           +dateDisplayed[2],
           +dateDisplayed[1] - 1,
           +dateDisplayed[0]
            );
    let firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    expect(dateToCompare).greaterThan(firstDayOfMonth);

When I run the tests I get the following output.

Cypress log test file

Does the 'expect' function modify my date values? It seems that both values are decreased by one day. How do I overcome this problem?

Thanks for your help!

Upvotes: 0

Views: 909

Answers (2)

Alapan Das
Alapan Das

Reputation: 18650

You can use day.js library for this. For assertion, you can apply the isAfter to compare both the dates like below:

const dayjs = require('dayjs')

describe('test suite', () => {
  it('Test', () => {
    let dateDisplayed = '22.07.2022'.split('.')
    let dateToCompare =
      dateDisplayed[2] +
      '-' +
      (+dateDisplayed[1] - 1).toString() +
      '-' +
      dateDisplayed[0]
    let firstDayOfMonth = dayjs().startOf('month') //2022-07-01T00:00:00+03:00
    const result = firstDayOfMonth.isAfter(dayjs(dateToCompare))
    cy.then(() => {
      expect(result).to.eq(true)
    })
  })
})

Upvotes: 0

mbojko
mbojko

Reputation: 14679

They aren't modified as much as translated from your time zone (Central European Summer Time, is it?) to GMT. Your midnight is 10pm in Greenwich.

Considering that it happened to both dates, it doesn't change the result of the comparison.

If it nevertheless bothers you, there's Cypress' clock function to influence how it handles, among other things, Date objects.

https://docs.cypress.io/api/commands/clock

Upvotes: 4

Related Questions