admin管理员组

文章数量:1316980

I'm trying to check if one date value that I get from the element in the app is less than today's date:

 const todaysDate = Cypress.moment().format('DD/MM/YYYY')

  it("Check date to be less or equal than todays", () => {
      cy.get('.date', { timeout: 15000 }).eq(3).invoke('text').should('be.lte', todaysDate);
    })

However I'm getting the following error:

Timed out retrying after 4000ms: expected '12/14/2020' to be a number or a date

Is there a way to convert the date I get from element to a datetime object?

I'm trying to check if one date value that I get from the element in the app is less than today's date:

 const todaysDate = Cypress.moment().format('DD/MM/YYYY')

  it("Check date to be less or equal than todays", () => {
      cy.get('.date', { timeout: 15000 }).eq(3).invoke('text').should('be.lte', todaysDate);
    })

However I'm getting the following error:

Timed out retrying after 4000ms: expected '12/14/2020' to be a number or a date

Is there a way to convert the date I get from element to a datetime object?

Share Improve this question asked Jan 12, 2021 at 15:00 Alex TAlex T 3,76415 gold badges69 silver badges126 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

You can use what JavaScript has to offer:

const date = new Date('12/14/2020');

so in the context of Cypress:

it("Check date to be less or equal than today", () => {
    cy
      .get('.date', { timeout: 15000 })
      .invoke('text')
      .then(dateText => {
        const date = new Date(dateText);
        const today = new Date();
        
        expect(date).to.be.lte(today);
    });
});

The moment library is deprecated, using dayjs is remended instead. You'll need this when parsing custom date formats, which might not be supported by the Javascript Date constructor. Based upon your error message I assume the expected format should be MM/DD/YYYY instead of DD/MM/YYY.

it("Check date to be less or equal than todays", () => {
    cy.get('.date', { timeout: 15000 }).invoke('text').then(actualDateText => {
        const dayjs = require('dayjs');
        const todaysDate = new Date();
        const actualDate = dayjs(actualDateText, 'MM/DD/YYYY').toDate();

        expect(actualDate).to.be.lte(todaysDate);
    });
});

本文标签: javascriptComparing two date values in cypressStack Overflow