Reputation: 3754
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?
Upvotes: 2
Views: 13457
Reputation: 8322
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);
});
});
Upvotes: 6
Reputation: 1577
The moment library is deprecated, using dayjs is recommended 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);
});
});
Upvotes: 2