Cypress Clock and Date Mock Not Working Fix
In this tutorial, you'll learn about Cypress Clock and Date Mock Not Working Fix. We cover key concepts, practical examples, and best practices.
Your cy.clock() doesn't freeze time — setTimeout callbacks fire at unexpected times, and Date.now() returns real time.
The Problem
// WRONG — clock created after timers already started
cy.visit('/');
cy.clock();
// The page already loaded with real timers
The page initializes timers during load using real time. cy.clock() is called too late — those timers are already running with real timing.
Step-by-Step Fix
1. Set clock before visit
// RIGHT — clock before page loads
cy.clock();
cy.visit('/');
// Now all timers are frozen
cy.tick(5000);
2. Control specific timers
// RIGHT — advance time precisely
cy.clock();
cy.visit('/');
// Advance by 1 second
cy.tick(1000);
// Advance by another 2 seconds
cy.tick(2000);
3. Mock Date with clock
// RIGHT — frozen Date
cy.clock(new Date('2024-06-15').getTime());
cy.visit('/');
const date = new Date();
expect(date.getFullYear()).to.equal(2024);
4. Restore clock
// RIGHT — clean up
beforeEach(() => {
cy.clock();
cy.visit('/');
});
afterEach(() => {
cy.clock().then((clock) => clock.restore());
});
Expected output:
✓ controls setTimeout
✓ advances time precisely
✓ mocks Date
Prevention Tips
- Call
cy.clock()beforecy.visit()to catch all timers - Use
cy.tick(ms)to advance time - Pass a Date or timestamp to
cy.clock()to set initial time - Restore clock in
afterEachto prevent leaks - Use
cy.clock().then(clock => clock.restore())for cleanup
Common Mistakes with clock date
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world CYPRESS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro