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.
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!
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.
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)
})
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.