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 setTimeout
, setInterval
, 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:
- Visit the Page: Navigate to the HTML page.
- Initialize Clock: Call
cy.clock()
to start using the simulated clock. - Start Timer: Simulate a click on the button to start the timer.
- Advance Clock: Use
cy.tick(3000)
to fast-forward the clock by 3 seconds, triggering the setTimeout
. - Verify Output: Assert that the message is displayed after the time has passed.
Output:
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:
- Visit the Initial Page: Navigate to the starting page of the application.
- Initialize Clock: Call
cy.clock()
to start using the simulated clock. - Start Interval: Simulate a click on the button to initiate the interval.
- Advance Clock: Use
cy.tick(6000)
to fast-forward the clock by 6 seconds, which will trigger the interval 5 times. - Verify Count: Assert that the counter reached 5 after the specified time.
Output:
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.
Similar Reads
Cypress - click() Method
The click() method in Cypress is a command that simulates a click event on an element. It can be used to interact with web pages in a way that mimics how a user would click on an element. This method can also be used to test web applications.Usages of Cypress - click() MethodIt simulates a click eve
3 min read
Cypress - check() Method
Cypress is a popular testing framework for web applications. It provides a lot of useful methods to interact with web pages, including the check() method. In this article, we will explore the check() method in Cypress, its usage, syntax, arguments, and examples.Usages of Cypress - check() MethodThe
3 min read
Cypress - clear() Method
The Cypress clear() method is a powerful tool used to clear the values of form elements, such as input fields and text areas. In this article, we will explore the Cypress clear method in detail, including its syntax, usage, and examples.SyntaxThe syntax for the Cypress clear method is as follows:cy.
2 min read
Cypress - clearCookie() Method
In web testing, cookies play a crucial role in maintaining session states, storing user preferences, and tracking user behavior. When running tests in Cypress, there might be scenarios where you need to clear specific cookies to test how your application behaves without them. The clearCookie() metho
4 min read
Cypress - clearCookies() Method
Cookies are small pieces of data stored by the browser that help maintain user sessions, track user preferences, and store other information. In automated testing with Cypress, managing cookies is essential for ensuring clean test environments and simulating different user scenarios. The clearCookie
4 min read
Cypress - as() Method
The as() method in Cypress is used to create aliases for elements or other values, which can then be referenced later in your tests. This is useful for making your tests more readable and efficient by avoiding repetitive code and simplifying complex selectors.Table of ContentUsageSyntaxArgumentsExam
4 min read
Cypress - clearAllCookies() Method
Cypress is a tool that helps us test websites automatically. It has many useful features that allow us to interact with websites differently. One of these features is called clearAllCookies(), which is used to delete all cookies that are stored in the browser.Usages The clearAllCookies() method is u
3 min read
Cypress - eq() Method
The eq() method in Cypress is a powerful utility that allows you to select a specific element from a group of elements based on its index. This method is particularly useful when you need to interact with or make assertions on a specific element within a collection of elements that share the same se
3 min read
Cypress - go() Method
In Web Application Testing, it is important to ensure users can smoothly navigate between pages using the browser's back and forward buttons. This is where the Cypress go() method comes to the rescue. Cypress, a popular testing framework, offers the cy.go() method that helps us move backwards or for
5 min read
Cypress - log() Method
The log() method in Cypress is a debugging tool that allows us to log custom messages to the Cypress Command Log during test execution. This method can help track the flow of our tests and debugging issues and provide contextual information about the actions being performed.Syntax:cy.log(message, op
4 min read