What is Cypress Clock()

Understand what Cypress clock is and how to use it. Also, learn how to enhance your Cypress tests via BrowserStack.

Get Started free
Home Guide Understanding Cypress Clock() : A Tutorial

Understanding Cypress Clock() : A Tutorial

By Ayush Singh, Community Contributor -

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

It is primarily used for speeding up tests 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 test efficiency and reliability.

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

What is Cypress Clock?

The Cypress Clock is a built-in utility that allows you to control the timings of your tests. It can freeze the clock, allowing you to manipulate time-based functions, and it can also advance time with the “cy.tick()” command.

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 used to move the clock forward by a specified number of milliseconds. This command effectively triggers any timers that would have been used during that interval.

Here’s how you can use cy.tick():

cy.clock();

cy.visit('your-app-url');

cy.tick(1000);

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

clock.restore()

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

Here’s an example of using clock.restore():

cy.clock();

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

Benefits of Using Cypress Clock

Given below are the benefits of using Cypress Clock:

  • Time Manipulation: Controls the flow of time in your tests, letting you manage delays and immediate executions without real time waiting.
  • Remove Idle Times: Get past unnecessary waiting periods in asynchronous operations easily. This helps streamline test execution.
  • Save Time: Reduces overall test time by eliminating long-running operations. This helps you provide faster feedback on the development.
  • Improved Test Reliability: Analyse the consistent behaviour of the time-dependent functions easily and make tests more predictable and robust.
  • Easy Debugging: Control when timers and intervals should execute and hence simplify the debugging process for time-related issues.
  • Enhanced Performance: Optimize your complete test performance by minimizing the dependence on real-time events and accelerating iterations.

How to Use Cypress Clock: Use Cases and Examples

Use commands like cy.tick(), cy.clock(), and clock.restore(), to effectively control the timing of your application’s behavior.

Here are some practical use cases and examples to understand the concept of Cypress Clock:

1. Trigger a setInterval

By triggering “setInterval” function using Cypress Clock, you can fast forward the time. This lets you test how your application responds to repeated actions over time without waiting for each interval to elapse in real time.

Here is an example of this use case:

cy.clock();

let count = 0;

setInterval(() => {

  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 useful for testing scenarios where you need to verify the state of your application after a certain period has passed, all while keeping your tests efficient.

Here is an example 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 call “clock.restore()” to return all overridden timing functions to their original state and to run all your tests with standard behavior.

Here is an example of this use case:

cy.clock();

cy.tick(2000);

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

4. Specify a Now Timestamp

When freezing the clock, specifying a custom timestamp can help you manage multiple conditions in your application. As a result, you can test how your application behaves at particular moments in time, 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 freezing the clock. This allows for more targeted testing strategies as it allows more control over which timers or intervals should be affected during tests.

Here is an example of this use case:

cy.clock();

This freezes all the timers.

6. Change Current System Time

Changing the current system time with Cypress Clock helps you check different time zones or specific dates within your application. Features that depend on date and time calculations can be tested via this approach. This will ensure 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 noted while using Cypress Clock:

  • Iframes Not Supported: Cypress Clock does not function with Iframes due to its inability for direct access to the DOM of an iframe directly.
  • Clock Behavior Before “cy.mount()”: Always set the clock before mounting components in your tests. If you attempt to manipulate time after a component is mounted, it will lead to unpredictable behavior and failed results.
  • Clock Behavior Before “cy.visit()”: Call ‘cy.clock()’ before visiting a page. This allows you to control the timing of any time-dependent functions that might execute as soon as the page loads.
  • Chaining Requirement: The ‘cy.clock()’ command must be chained off of “cy.”. This means it cannot stand alone and should always be part of a command chain to ensure proper execution.
  • No Assertions on “cy.tick()”: Keep in mind that assertions cannot be run immediately after cy.tick().
  • Avoid Overusing Time Manipulation: While Cypress Clock is powerful for controlling time, overusing it can lead to complex and cumbersome tests

Talk to an Expert

Run your Cypress Tests on Real Devices

Running Cypress tests on mobile devices is not very easy and it comes with certain limitations.

This challenge can be overcome by running your Cypress tests on platforms like BrowserStack Automate.

With the help of this tool, you can easily access thousands of real mobile devices and browsers. This ensures that your application is not only functional but also provides a seamless user experience on different screen sizes and operating systems.

This cloud-based solution allows you to replicate real-world user conditions, ensuring that your application behaves correctly under several conditions, like network speeds and device configurations.

Key Benefits of Using BrowserStack Automate

  • Cross-Browser Testing: Validate your application’s performance across multiple browsers and versions, and identify any compatibility issues before they affect users.

BrowserStack Automate Banner

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

Vue.js Sample Code:

<template>

  <div data-test="number">{{ number }}</div>

</template>



<script lang="ts" setup>

import { onMounted, ref } from 'vue';



const number = ref(0);



onMounted(() => {

  setInterval(() => {

number.value += 1;

}, 1000);

});

</script>

Here is the code for a Cypress test to automate this component:

describe('Timer Component Test', () => {

  beforeEach(() => {

cy.clock(0, ['setInterval']);

cy.visit('http://localhost:3000/#/index/dashboardview2');

});



  it('should increment the number every second', () => {

cy.get('[data-test="number"]').should('have.text', '0');

cy.tick(1000);

cy.get('[data-test="number"]').should('have.text', '1');



cy.tick(1000);

cy.get('[data-test="number"]').should('have.text', '2');

  });



  it('should correctly increment after multiple ticks', () => {

cy.get('[data-test="number"]').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 parallel tests across multiple devices, and decrease the time required for comprehensive testing cycles.

Conclusion

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

By allowing precise control over time-dependent functions, Cypress Clock enables developers to manage multiple scenarios without the delays associated with real time execution. This not only accelerates the testing process but also provides accurate test results.

Run your Cypress tests on tools like BrowserStack Automate, to take your experience of testing to another level with its advanced real device testing features.

Try BrowserStack Now

Frequently Asked Questions

1. What is the difference between Cypress and Nightwatch?

Cypress offers a more interactive testing experience with real-time reloading and debugging features, while Nightwatch focuses on Selenium-based testing with a low focus on the developer experience.

2. When not to use Cypress?

Avoid using Cypress to test applications that require multi-tab support or extensive support for iframes.

3. Can Cypress do visual testing?

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

Useful Resources for Cypress

Understanding Cypress

Use Cases

Tool Comparisons

Tags
Automation Testing Cypress Website Testing

Featured Articles

How to handle Cypress Asynchronous Behavior?

How to Handle Dropdown in Cypress

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers