Open In App

Cypress - clock() Method

Last Updated : 23 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The clock() method in Cypress is used to control and manipulate the clock in our tests. This allows developers to test time-dependent code more effectively by controlling the passage of time and simulating the behavior of timers and intervals.

Syntax:

cy.clock()

Usage of Cypress - clock() Method

The clock() method is typically used when we want to pause the real-time clock and use a simulated clock instead. This is especially useful for testing scenarios that involve setTimeoutsetInterval, or any other time-related functions.

Arguments

The clock() method does not take any arguments. It simply initializes a simulated clock for use in our tests.

Examples

Example 1: Testing a Timer with setTimeout

In this example, we’ll use clock() to test a function that uses setTimeout to delay an action.

HTML File (index1.html): Save this HTML file in our local server directory (e.g., localhost:3000)

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Page - Clock Example 1</title>
</head>
<body>
    <button class="start-timer">Start Timer</button>
    <div class="message" style="display:none;">Timer Finished!</div>

    <script>
        document.querySelector('.start-timer').addEventListener('click', function() {
            setTimeout(function() {
                document.querySelector('.message').style.display = 'block';
            }, 3000); // 3 seconds delay
        });
    </script>
</body>
</html>

Cypress Test File (clock_example1_spec.js)
Save this file in the cypress/e2e (for Cypress v10 and above) or cypress/integration (for older versions) folder of our Cypress project

JavaScript
describe('Using `clock()` Method', () => {
    beforeEach(() => {
        // Visit the test application
        cy.visit('http://localhost:3000/index1.html');
    });

    it('should show message after timer finishes', () => {
        // Start the clock
        cy.clock(); // Initialize the simulated clock

        // Click the button to start the timer
        cy.get('.start-timer').click();

        // Advance the clock by 3 seconds
        cy.tick(3000); // Move the clock forward by 3000 milliseconds

        // Verify that the message is displayed
        cy.get('.message').should('be.visible');
    });
});

Explanation:

  1. Visit the Page: Navigate to the HTML page.
  2. Initialize Clock: Call cy.clock() to start using the simulated clock.
  3. Start Timer: Simulate a click on the button to start the timer.
  4. Advance Clock: Use cy.tick(3000) to fast-forward the clock by 3 seconds, triggering the setTimeout.
  5. Verify Output: Assert that the message is displayed after the time has passed.

Output:

clock11


After advancing the clock, the message should become visible immediately, demonstrating that the timer functionality works as expected.

Example 2: Testing an Interval with setInterval

In this example, we’ll use clock() to test a function that uses setInterval to perform an action repeatedly.

HTML File (index2.html): Save this HTML file in our local server directory (e.g., localhost:3000)

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Page - Clock Example 2</title>
</head>
<body>
    <button class="start-interval">Start Interval</button>
    <div class="count" style="display:none;">Count: <span id="counter">0</span></div>

    <script>
        let count = 0;
        document.querySelector('.start-interval').addEventListener('click', function() {
            setInterval(function() {
                count++;
                document.getElementById('counter').innerText = count;
                if (count >= 5) {
                    clearInterval(this);
                }
            }, 1000); // 1 second interval
            document.querySelector('.count').style.display = 'block';
        });
    </script>
</body>
</html>

Cypress Test File (clock_example2_spec.js)
Save this file in the cypress/e2e (for Cypress v10 and above) or cypress/integration (for older versions) folder of our Cypress project

JavaScript
describe('Using `clock()` Method with Intervals', () => {
    beforeEach(() => {
        // Visit the initial page
        cy.visit('http://localhost:3000/index2.html');
    });

    it('should count up to 5', () => {
        // Start the clock
        cy.clock(); // Initialize the simulated clock

        // Click the button to start the interval
        cy.get('.start-interval').click();

        // Advance the clock by 6 seconds to allow for 5 counts
        cy.tick(6000); // Move the clock forward by 6000 milliseconds

        // Verify that the count reached 5
        cy.get('#counter').should('have.text', '5');
    });
});

Explanation:

  1. Visit the Initial Page: Navigate to the starting page of the application.
  2. Initialize Clock: Call cy.clock() to start using the simulated clock.
  3. Start Interval: Simulate a click on the button to initiate the interval.
  4. Advance Clock: Use cy.tick(6000) to fast-forward the clock by 6 seconds, which will trigger the interval 5 times.
  5. Verify Count: Assert that the counter reached 5 after the specified time.

Output:

clock22

After advancing the clock, the count should display 5, demonstrating that the interval functionality works as expected.

Conclusion

The clock() method in Cypress is an essential tool for testing time-dependent code. By controlling the passage of time, developers can effectively test features that rely on timers and intervals, making their tests more reliable and easier to debug.


Next Article

Similar Reads