Test Timers and Reduce the Wait with Cypress’ Cy.Clock

Testing timers reliably is a difficult task because time changes and must be synced between different places. In manual tests, you need to wait out long timers to make sure that they fire correctly. This is unacceptable for automated testing environments where the goal is to have the tests run quickly and regularly. To avoid waiting, Cypress has a built-in method cy.clock() that turns coders into Time Lords.

How to Use Cy.clock:

Calling cy.clock() gives the Cypress test control of the client’s clock. Any calls to clock.now() will return the time that cy.clock() was called. Cy.clock gives an opportunity to check the initial state of the page or component. To move the clock forward, use cy.tick() with a number of milliseconds. Cy.tick() moves the clock forward. Then, it checks for any setTimeout or setInterval events that expired in between the previous time and the new time.

See an example of this below:

 setTimeout(() => {
console.log('Its been 5 seconds.');
}, 5000);

setTimeout(() => {
console.log('Its been 8 seconds.');
}, 8000);


//skip forward 10 seconds



When to Use Cy.clock:

Cy.clock() integrates mostly smoothly with components that don’t interact with timers outside of the client. Examples include animations and sending requests. Cy.clock() struggles when the behavior of the component is dependent on an external timer. An example would be asking the server how long a user has been logged in. The test may need to sync the clocks between the frozen Cypress clock and the server’s real-time clock.

Using Cy.clock for a Stable Test Environment

Cypress offers a strong set of features for testing front-end applications and the clock method is one of them. It provides a stable environment to test a component or page’s behavior and ensures the tests can be run more quickly to better fit into a deployment pipeline.


Join the conversation

Your email address will not be published. Required fields are marked *