'Stub "new Date()" with Cypress

In my tests, "new Date()" returns the current date, but I want it return a constant object. But I don't know how to stub this. Example of what I would like :

cy.stub(Date, 'constructor', () => {
  return new Date(2020, 6, 24, 22, 19, 00)
})

How to do this ? Thanks



Solution 1:[1]

Try this approach:

cy.clock(new Date(2020, 6, 24, 22, 19, 00), ['Date'])

Solution 2:[2]

Refer: Specify a now timestamp.

In app code:

// element
<div id="mockedDate"></div>

// script
document.getElementById('mockedDate').innerText = new Date();
it('stub date', () => {
    cy.clock(new Date(2020, 6, 24, 22, 19, 0).getTime());
    cy.visit('http://localhost:8081/?j=test');
    cy.get('#mockedDate').invoke('text').then(cy.log);
});

screenshot

Solution 3:[3]

Not sure about cy.stubbing the Date, but for anyone experiencing issues when using cy.clock & having all sorts of setIntervals which break the cy.visit, etc.

I was able to mock the new Date() by simply overwriting the global win.Date

my.spec.ts

export class FakeDate extends Date {
  constructor(date) {
    super(date)
    if (date) {
      return new Date(date)
    }
    // The date you want
    return new Date('Fri Apr 29 2022 01:59:59 GMT+0200 (Central European Summer Time)')
  }
}
// ...
cy.visit('my-page', {
  onBeforeLoad(win) {
    win.Date = FakeDate
  }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 amolinaalvarez
Solution 2
Solution 3 htmn