Reputation: 2445
In my Cypress test, I am trying to compare a date value retrieved from a MySQL DB to the date appearing on the UI.
Here is my assertion:
cy.compareDates(result[0].publishdate, companyDetails.publishedDate())
result[0].publishdate
is the value retrieved from the database - 2022-02-14 16:45:37
(expectedDate
below).
companyDetails.publishedDate()
is the UI element that contains the text 14-Feb-2022
(actualDate
below).
Here is my compareDates()
function:
Cypress.Commands.add('compareDates', (expectedDate, actualDate) => {
actualDate.then(date => {
const reformattedDate = new Date(date.text())
cy.log('reformat: ' + reformattedDate)
cy.log('ISO string: ' + reformattedDate.toISOString().split('T')[0])
// expect(reformattedDate.toISOString().split('T')[0]).to.equal(expectedDate.split('T')[0])
})
})
The assertion that I have commented out returns this failure:
And here are the values being used:
Reformatted Date: Fri Sep 11 2015 00:00:00 GMT+0100 (British Summer Time)
ISO string: 2015-09-10
What is strange is that the function is working with the below dates:
Reformatted Date: Wed Feb 28 2007 00:00:00 GMT+0000 (Greenwich Mean Time)
ISO string: 2007-02-28
Upvotes: 0
Views: 223
Reputation: 31904
Going back to the original question
In my Cypress test, I am trying to compare a date value retrieved from a MySQL DB to the date appearing on the UI.
The value appearing on the UI is
14-Feb-2022
.The value in the database is
2022-02-14 16:45:37
since they are both strings (from comments), you can compare them with less hassle using dayjs.
Basically, dayjs is really good at parsing date strings into date objects (however the documentation is a bit on the brief side)
For example:
const dayjs = require('dayjs')
it('tests my dates', () => {
const dateFromUI = dayjs('14-Feb-2022')
const dateFromDb = dayjs('2022-02-14 16:45:37')
console.log(dateFromField, dateFromDb)
})
You get objects back from dayjs(myDateString)
that have properties for each of the parts of the date.
So if you want to compare year, month, day and ignore time
expect(dateFromUI.$y).to.eq(dateFromDb.$y)
expect(dateFromUI.$M).to.eq(dateFromDb.$M)
expect(dateFromUI.$D).to.eq(dateFromDb.$D)
There are other ways to do the comparison, for example $d
property has a string representation Mon Feb 14 2022 16:45:37
and you can do a substring comparison to ignore the time portion.
Or there are diff methods, for example:
dateFromUI.isSame(dateFromDb, 'day') // returns true
Upvotes: 1