Understanding Cypress Clock() : A Tutorial

On This Page What is Cypress Clock?cy.tick()May 24, 2026 · 8 min read · Tool Comparison

Understanding Cypress Clock (): A Tutorial

Cypress Clock is an advanced lineament of the Cypress framework. It allows you to moderate and manipulate time in tests.

It is chiefly utilise for rush up trial that involve timers or asynchronous operations, such as “setTimeout” or “setInterval”.

By using Cypress Clock, developers can modify the passage of time without waiting for the real-time to elapse, thus improving examination efficiency and reliability.

Learn more about the Cypress Clock, its syntax, use cases, benefits, etc. with this guidebook.

What is Cypress Clock?

The Cypress Clock is a built-in usefulness that allows you to check the timings of your trial. It can freeze the clock, allowing you to fake time-based map, and it can besides advance time with the “cy.tick()” dictation.

The basic syntax for using Cypress Clock is as follows:

cy.clock ([now]);

Usage of (now):An optional parameter that specifies a timestamp to set the clock. If not provided, the clock will start at the current time.

cy.tick()

The cy.tick () command is habituate to move the clock forward by a specified routine of milliseconds. This command efficaciously triggers any timers that would have been employ during that interval.

Here & # 8217; s how you can use cy.tick ():

cy.clock (); cy.visit ('your-app-url '); cy.tick (1000);

In this instance, if there are any “ setTimeout ” or “ setInterval ” functions scheduled to action within that 1-second window, they will be triggered immediately.

clock.restore ()

The clock.restore () method is used to rejuvenate all overridden native time functions back to their original province. This is particularly useful when you desire to stop manipulating clip after a series of tests.

Here & # 8217; s an example of using clock.restore ():

cy.clock (); cy.clock () .invoke ('restore ');

Read More:

Benefits of Using Cypress Clock

Given below are the benefits of use Cypress Clock:

  • Time Manipulation: Controls the flow of time in your tests, allow you manage delays and immediate executions without real time await.
  • Remove Idle Times:Get past unnecessary waiting period in asynchronous operations well. This helps streamline test executing.
  • Save Time:Reduces overall test time by eliminating long-running operation. This helps you provide faster feedback on the growing.
  • Improved Test Reliability:Analyse the consistent behaviour of the time-dependent functions easily and make tests more predictable and robust.
  • Leisurely Debugging: Control when timers and separation should execute and hence simplify the debugging procedure for time-related issues.

Read More:

  • Enhanced Performance: Optimize your complete tryout performance by minimizing the dependency on real-time events and accelerating loop.

How to Use Cypress Clock: Use Cases and Examples

Use commands likecy.tick(), cy.clock (), and clock.restore (), to efficaciously control the timing of your coating ’ s behavior.

Here are some practical use cases and exemplar to interpret the conception of Cypress Clock:

1. Trigger a setInterval

By triggering “setInterval” function apply Cypress Clock, you can fast forward the time. This lets you try how your coating reply to repeated actions over clip without waiting for each interval to elapse in real clip.

Here is an model of this use causa:

cy.clock (); let count = 0; setInterval (() = & gt; {count++;}, 1000); cy.tick (3000); expect (count) .to.equal (3);

2. Move Time Synchronously

It allows to advance the clock by a specified amount of milliseconds. This is primarily utile for try scenario where you need to verify the province of your coating after a certain period has pass, all while hold your tests efficient.

Here is an illustration of this use case:

cy.clock (); cy.visit ('your-app-url '); cy.tick (5000);

3. Restore Native Functions

This is one of the most important aspects of using Cypress Clock effectively. After manipulating the clock for your tests, you can telephone “clock.restore ()” to return all overridden timing functions to their original state and to run all your tests with standard behavior.

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

Here is an example of this use instance:

cy.clock (); cy.tick (2000); cy.clock () .invoke ('restore ');

4. Specify a Now Timestamp

When freezing the clock, specifying a customs timestamp can help you manage multiple weather in your application. As a issue, you can essay how your application behaves at particular moments in clip, providing greater control over time-dependent functionalities.

Here is an example of this use case:

const now = new Date (Date.UTC (2024, 0, 1)) .getTime (); cy.clock (now);

5. Specify Functions to Override

With Cypress Clock, you can specify which functions you want to override when freeze the clock. This countenance for more targeted screen strategies as it allows more control over which timers or intervals should be affected during tests.

Here is an example of this use suit:

cy.clock (); This freezes all the timekeeper.

6. Change Current System Time

Changing the current system time with Cypress Clock helps you check different time zones or specific dates within your covering. Features that depend on date and time figuring can be tested via this approach. This will check that the application behaves correctly under different conditions.

Here is an example of this use case:

const newTime = new Date (Date.UTC (2024, 0, 1)) .getTime (); cy.clock (newTime);

Key Points to Remember While Using Cypress Clock

Here are some of the points to be observe while utilize Cypress Clock:

  • Iframes Not Supported:Cypress Clock make not officiate with Iframes due to its unfitness for unmediated admittance to the DOM of an iframe forthwith.
  • Clock Behavior Before “ cy.mount () ”: Always set the clock before mounting part in your examination. If you attempt to manipulate clip after a component is mounted, it will lead to unpredictable behavior and failed results.
  • Clock Behavior Before “ cy.visit () ”: Call ‘cy.clock ()’ before visit a page. This allows you to control the timing of any time-dependent functions that might execute as presently as the page lade.
  • Chaining Requirement: The ‘cy.clock ()’ dictation must be chained off of “cy. ”. This means it can not stand alone and should constantly be part of a command chain to see proper execution.
  • No Assertions on “ cy.tick () ”:Keep in mind that assertions can not be run immediately aftercy.tick().
  • Avoid Overusing Time Manipulation: While Cypress Clock is powerful for controlling clip, overusing it can conduct to complex and cumbersome tests

Talk to an Expert

Run your Cypress Tests on Real Devices

is not very easy and it comes with sure limitations.

This challenge can be overpower by running your Cypress tests on platforms like

With the help of this creature, you can easily access thousands of real mobile device and browser. This ensures that your application is not only functional but also ply a seamless user experience on different screen sizing and operating systems.

This cloud-based solution allows you to replicate real-world user weather, ensuring that your application do aright under various conditions, like web fastness and twist configurations.

Key Benefits of Using BrowserStack Automate

  • Validate your application ’ s performance across multiple browsers and versions, and identify any compatibility issues before they impact users.

Read More:

  • Seamless Integration: Easily, allowing for smooth test executing without extensive shape changes.

Here ’ s an example of automating a timer component that updates its state based on a timer.

Vue.js Sample Code:

& lt; templet & gt; & lt; div & gt; {{routine}} & lt; /div & gt; & lt; /template & gt; & lt; script lang= '' ts '' setup & gt; import {onMounted, ref} from 'vue '; const number = ref (0); onMounted (() = & gt; {setInterval (() = & gt; {number.value += 1;}, 1000);}); & lt; /script & gt;

Here is the code for a Cypress trial to automatise this ingredient:

describe ('Timer Component Test ', () = & gt; {beforeEach (() = & gt; {cy.clock (0, ['setInterval ']); cy.visit ('http: //localhost:3000/ # /index/dashboardview2 ');}); it ('should increment the number every second ', () = & gt; {cy.get (' [data-test= '' number ''] ') .should ('have.text ', ' 0 '); cy.tick (1000); cy.get (' [data-test= '' routine ''] ') .should ('have.text ', ' 1 '); cy.tick (1000); cy.get (' [data-test= '' number ''] ') .should ('have.text ', ' 2 ');}); it ('should correctly increment after multiple ticks ', () = & gt; {cy.get (' [data-test= '' bit ''] ') .should ('have.text ', ' 0 '); cy.tick (3000); cy.get (' [data-test= '' number ''] ') .should ('have.text ', ' 3 ');});});
  • Real-Time Debugging: Manage live interactive sessions to debug issues in real time, making identifying and resolving problems during testing easier.
  • Automated Testing at Scale: Run across multiple devices, and decrease the clip required for comprehensive testing cycles.

Read More:

Conclusion

Using Cypress Clock in your testing workflow helps in improve the efficiency and reliableness of your tests.

By allowing precise control over time-dependent map, Cypress Clock enables developer to manage multiple scenario without the delays consort with real time performance. This not only accelerates the testing process but also provides exact test termination.

Run your Cypress tests on tools like BrowserStack Automate, to take your experience of testing to another grade with its advanced existent device testing feature.

Frequently Asked Questions

1. What is the difference between Cypress and Nightwatch?

Cypress offers a more interactive screen experience with real-time reloading and debugging lineament, while Nightwatch concentrate on Selenium-based testing with a low focusing on the developer experience.

2. When not to use Cypress?

Avoid expend Cypress to test applications that require multi-tab support or panoptic support for iframes.

3. Can Cypress do optical testing?

Yes, Cypress can perform optical testing using plugins like “ cypress-image-snapshot ”.

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
87,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free