To harness the power of “Cypress clock” for precise test timing and control, here are the detailed steps:
👉 Skip the hassle and get the ready to use 100% working script (Link in the comments section of the YouTube Video) (Latest test 31/05/2025)
Check more on: How to Bypass Cloudflare Turnstile & Cloudflare WAF – Reddit, How to Bypass Cloudflare Turnstile, Cloudflare WAF & reCAPTCHA v3 – Medium, How to Bypass Cloudflare Turnstile, WAF & reCAPTCHA v3 – LinkedIn Article
First, understand its purpose: Cypress’s cy.clock
allows you to manipulate the browser’s native setTimeout
, setInterval
, Date
, and requestAnimationFrame
functions.
This is crucial for testing time-sensitive features without waiting for real-world delays.
Here’s a quick guide:
-
To start mocking time:
cy.clock.
This freezes time at the moment
cy.clock
is called.
Any subsequent Date
calls will return this mocked time, and setTimeout
/setInterval
won’t fire until you explicitly advance the clock.
-
To advance time:
cy.tickmilliseconds.Example:
cy.tick1000.
advances the clock by 1 second, causing any timers scheduled within that second to fire. -
To mock a specific date and time:
Cy.clocknew Date2023, 0, 1, 12, 0, 0. // Jan 1, 2023, 12:00:00 PM
This sets the initial mocked time to a specific point.
-
To restore the real clock:
cy.clock.invoke’restore’.It’s good practice to restore the clock after tests that use
cy.clock
to prevent interference with subsequent tests. -
For more detailed scenarios, explore these resources:
- Cypress
cy.clock
documentation: https://docs.cypress.io/api/commands/clock - Cypress
cy.tick
documentation: https://docs.cypress.io/api/commands/tick - Blog post on testing time-dependent features: https://www.cypress.io/blog/2019/04/10/testing-time-dependent-features/ Note: Check for the latest Cypress blog as links may change
- Cypress
By mastering cy.clock
, you’ll gain significant control over your test environment, leading to faster, more reliable, and less flaky end-to-end tests for any application features that rely on time.
Understanding the Core Mechanism of cy.clock
cy.clock
in Cypress isn’t just a simple utility.
It’s a powerful tool that deeply integrates with the browser’s JavaScript runtime to intercept and control time-related functions.
Think of it as a time machine for your tests, allowing you to fast-forward, rewind, or even freeze the flow of time within your application’s environment.
This capability is paramount for testing asynchronous operations that are time-bound, such as debouncing, throttling, animations, countdowns, and cache expirations, without having to wait for actual wall-clock time to elapse.
Without cy.clock
, testing such features would either be incredibly slow waiting for real timeouts or highly unreliable prone to race conditions.
How cy.clock
Intercepts Time
When you call cy.clock
, Cypress effectively replaces the browser’s native global Date
, setTimeout
, setInterval
, and requestAnimationFrame
objects with its own mocked versions.
This interception happens at a fundamental level, meaning any code in your application that calls these functions will interact with Cypress’s mocked clock instead of the real one.
Date
Object Mocking: Whency.clock
is active, anynew Date
orDate.now
calls in your application will return a time based on Cypress’s internal mocked clock, not the system’s real time. This is invaluable for testing features that display or process dates, ensuring consistency across test runs regardless of when they are executed.- Timer Function Control:
setTimeout
andsetInterval
are perhaps the most common use cases. Normally, these functions schedule callbacks to run after a certain delay. Withcy.clock
enabled, these callbacks are not automatically executed after their specified delay. Instead, they are queued internally by Cypress, waiting for you to explicitly advance the mocked time usingcy.tick
. This gives you precise control over when these time-dependent events occur. - Animation Frame Manipulation
requestAnimationFrame
: For animations,requestAnimationFrame
is key.cy.clock
also mocks this function, allowing you to control animation progression frame by frame usingcy.tick
, which is crucial for testing animation states and transitions without visual inspection.
Benefits of Mocking Time
The advantages of using cy.clock
are numerous and impactful on the efficiency and reliability of your test suite.
- Faster Test Execution: This is arguably the biggest benefit. Instead of
cy.wait5000
to simulate a 5-second delay, you can usecy.tick5000
. Thecy.tick
command completes almost instantaneously, as it simply advances an internal counter and triggers queued events, drastically reducing test runtime. For large test suites, this can translate into hours of saved execution time daily. For example, if you have 10 tests each waiting for 10 seconds, that’s 100 seconds of real-time waiting. Withcy.tick
, it becomes milliseconds. - Elimination of Flakiness: Time-dependent tests are notoriously flaky because they rely on precise timing that can be affected by system load, network latency, or even minute differences in execution environments. By mocking time, you remove these external variables. Your tests become deterministic. if an event is supposed to happen after 200ms,
cy.tick200
will guarantee it happens exactly then, every time, regardless of the test runner’s current load. This significantly improves test stability, which, according to a recent survey among QA professionals, is a top concern, with 40% citing flakiness as their biggest challenge in automated testing. - Isolation and Predictability: Mocking time isolates your application’s time-sensitive logic from the real system clock. This means your tests will behave the same whether run at noon or midnight, on a fast machine or a slow one. This predictability is vital for maintaining a reliable continuous integration/continuous deployment CI/CD pipeline.
- Testing Edge Cases: It becomes trivial to test scenarios like timeouts occurring, specific date ranges e.g., leap years, end of months, or events that only happen after prolonged periods e.g., session expirations after 30 minutes. You can simply
cy.tick30 * 60 * 1000
to simulate a 30-minute wait in an instant.
Understanding these core mechanisms and benefits is foundational to effectively utilizing cy.clock
for building robust and efficient Cypress test suites. It’s not just a nice-to-have.
For many modern web applications, it’s an essential tool for comprehensive testing. Software testing standards
Practical Implementation: Getting Started with cy.clock
and cy.tick
Implementing cy.clock
and cy.tick
in your Cypress tests is straightforward once you understand the basic flow.
The key is to remember that cy.clock
“stops” time, and cy.tick
“advances” it.
This control allows you to meticulously orchestrate how time-dependent events unfold within your test environment.
Basic Usage: Freezing and Advancing Time
The most common pattern involves calling cy.clock
to freeze time at the beginning of a test and then using cy.tick
to trigger specific time-based events.
-
Start the Clock:
describe’Time-dependent feature’, => {
beforeEach => {cy.visit'/your-app'. // Navigate to your application cy.clock. // Freeze time at the current moment
}.
it’should trigger a debounced search after 500ms’, => {
cy.get''.type'Cypress'. // At this point, any debounced function is scheduled but not yet executed. cy.tick499. // Advance time just shy of the debounce delay cy.get''.should'not.exist'. // Assert that results haven't appeared yet cy.tick1. // Advance time by 1ms, hitting the 500ms mark cy.get''.should'be.visible'.and'contain', 'Cypress'. // Assert results are now visible
}.
In this example,
cy.clock
freezes time when the test starts.
When cy.get''.type'Cypress'
is executed, let’s assume a debounce function e.g., _.debounce
or a custom one schedules a search API call for 500ms later. Salesforce test automation tools
By calling cy.tick499
, we simulate almost the full delay without triggering the search.
Then, cy.tick1
completes the 500ms, causing the debounced function to execute instantly within the test.
This allows for precise control and rapid testing of debouncing behavior.
-
Mocking a Specific Date:
Sometimes, you need to test features that behave differently on specific dates e.g., promotions active during a certain month, age calculations. You can set the initial mocked time when you call
cy.clock
.It’should show a holiday banner on Christmas Day’, => {
// Set the clock to Christmas Day, 2023cy.clocknew Date2023, 11, 25, 10, 0, 0. // Month is 0-indexed 11 for December
cy.visit’/holiday-page’.cy.get”.should’be.visible’.and’contain’, ‘Merry Christmas!’.
It’should not show a holiday banner on a regular day’, => {
// Set the clock to a non-holidaycy.clocknew Date2023, 0, 15, 10, 0, 0. // January 15th Run javascript code in browser
cy.get”.should’not.exist’.
This demonstrates how easily you can switch the “current date” for your application to test date-specific logic without manually changing system dates or waiting for real time.
Restoring the Clock
It’s crucial to restore the original, un-mocked clock after your tests have completed.
If you don’t, subsequent tests in the same run might inherit the mocked clock state, leading to unexpected behavior and flakiness.
-
Using
afterEach
orafter
:Describe’Time-dependent feature with cleanup’, => {
cy.visit’/your-app’.
cy.clock. // Start mocking the clock
it’tests something time-dependent’, => {
// … test logic …
afterEach => {// Restore the clock to its original state after each test cy.clock.invoke'restore'.
Placing
cy.clock.invoke'restore'.
in anafterEach
hook ensures that every test gets a clean, un-mocked clock state, preventing side effects between tests.
If you only use cy.clock
in a single it
block and want to restore it immediately after that specific test, you can put the restore command at the end of that it
block.
Handling Multiple Timers
What if your application has multiple timers set at different intervals? cy.tick
intelligently fires all timers whose scheduled execution time falls within the advanced duration.
it'should handle multiple concurrent timers', => {
cy.visit'/multi-timer-app'.
cy.clock. // Freeze time
// Assume the app sets two timers: one for 1 second, one for 2 seconds.
cy.tick1000. // Advance by 1 second. The first timer fires.
cy.get''.should'contain', 'completed'.
cy.get''.should'not.contain', 'completed'. // Second timer hasn't fired yet
cy.tick1000. // Advance by another 1 second total 2 seconds. The second timer fires.
cy.get''.should'contain', 'completed'.
}.
This showcases how cy.tick
can orchestrate complex time flows, allowing you to verify the precise sequence of events. Mainframe testing
You can cy.tick
multiple times or use a single large cy.tick
call depending on what you need to assert at intermediate steps.
This precise control over event sequences makes cy.clock
an indispensable tool for robust application testing.
Advanced Techniques: Orchestrating Complex Time Scenarios
While basic cy.clock
and cy.tick
usage covers many scenarios, real-world applications often involve more intricate time-based logic.
Mastering advanced techniques allows you to test these complex interactions with precision and reliability, moving beyond simple delays to truly orchestrate your application’s timeline.
This includes handling asynchronous operations that involve time, such as network requests with specific timeouts, and effectively combining time manipulation with other Cypress commands like cy.intercept
.
Controlling Asynchronous Operations with Timeouts
Many network requests or long-running processes in web applications include timeouts.
If a response isn’t received within a certain period, the operation fails, or an alternative UI is shown.
cy.clock
can simulate these timeouts instantly.
-
Simulating API Request Timeouts:
Imagine an API call that times out after 5 seconds if there’s no response. Hotfix vs coldfix
It’should show an error if an API call times out’, => {
cy.clock. // Freeze time
cy.intercept’GET’, ‘/api/data’, {// Here, we don't return a fixture immediately. // Instead, we just let it hang, waiting for a clock tick.
}.as’getData’.
cy.visit’/data-display’. // This action initiates the API call
cy.tick4999. // Advance just before the 5-second timeout
cy.get”.should’not.exist’. // Error message should not be visible yet
cy.tick1. // Advance exactly to 5 seconds, triggering the timeout
cy.get”.should’be.visible’.and’contain’, ‘Request timed out’.
cy.wait’@getData’.its’response.statusCode’.should’equal’, 500. // Verify the network call failed
In this scenario,cy.intercept
is set up to not immediately respond. By usingcy.tick
to advance time, we control exactly when the application’s internal timeout logic kicks in. This is far more reliable thancy.wait
for a fixed duration, which might pass before the application’s actual timeout is triggered. -
Testing Debounced Inputs with Intermediate Types:
A common pattern for search inputs is debouncing, where the API call only fires after the user stops typing for a certain duration. User acceptance testing tools
Testing this precisely requires fine-grained time control.
it'should debounce search input correctly', => {
cy.clock.
cy.intercept'GET', '/api/search?q=Cypress', { fixture: 'search-cypress.json' }.as'searchCypress'.
cy.intercept'GET', '/api/search?q=Cypress.io', { fixture: 'search-cypressio.json' }.as'searchCypressIo'.
cy.visit'/search-page'.
cy.get''.type'Cypress'. // Type first part
cy.tick200. // Advance clock, but not enough to trigger debounce e.g., 500ms debounce
cy.get''.type'.io'. // Continue typing
cy.tick499. // Advance almost enough for the new debounce cycle
cy.get''.should'not.exist'. // No search yet
cy.tick1. // Final tick to trigger the debounce
cy.wait'@searchCypressIo'. // Verify only the final search was made
cy.get''.should'be.visible'.and'contain', 'Cypress.io'.
This demonstrates how `cy.tick` allows you to simulate user typing, pause, then continue, and verify that the debounce logic correctly waits for the *last* input before triggering the search. This level of control is impossible with real time.
Combining with cy.intercept
for Network Control
The synergy between cy.clock
and cy.intercept
is incredibly powerful.
While cy.clock
controls client-side time, cy.intercept
controls network responses.
Together, they allow you to test a wide array of time- and network-dependent scenarios.
-
Delaying API Responses Manually:
You might want to test loading states or optimistic UI updates.
Instead of using cy.wait
with an arbitrary duration, you can hold an cy.intercept
response and then explicitly release it with cy.tick
.
it'should show a loading spinner while data is fetching', => {
let sendResponse. // A variable to hold the response control
cy.intercept'GET', '/api/long-load', req => {
return new Cypress.Promiseresolve => {
sendResponse = fixture => {
req.reply{ fixture: fixture, delay: 0 }. // Reply instantly once we choose to
resolve.
}.
}.
}.as'longLoad'.
cy.visit'/dashboard'. // Initiates the long load
cy.get''.should'be.visible'.
cy.tick1000. // Advance clock - loading spinner should still be there
// Now, simulate the server responding after a delay e.g., 2 seconds of real time
// This is where you would call sendResponse if it were a real delay,
// but with cy.clock, we control when it's resolved.
sendResponse'dashboard-data.json'. // Manually send the response
cy.get''.should'not.exist'.
cy.get''.should'be.visible'.
This example uses a `Cypress.Promise` within `cy.intercept` to manually control when the response is sent. While `cy.tick` isn't directly causing the *network* response here, it allows you to verify UI states like loading spinners that depend on the *passage of time* during which a network request might be pending. The `sendResponse` function can be triggered at any point, combined with `cy.tick` to simulate the precise timing of the API call completing and UI updates. This offers unparalleled control for testing complex loading and error states.
Understanding cy.clock
and requestAnimationFrame
For smooth animations, browsers use requestAnimationFrame
. cy.clock
also intercepts this, allowing you to step through animations frame by frame.
it’should animate an element over time’, => {
cy.clock.
cy.visit’/animation-page’.
cy.get”.as’box’.
// Trigger animation e.g., by clicking a button
cy.get”.click. Reusability of code
// Initial state
cy.get’@box’.should’have.css’, ‘transform’, ‘none’. // Or initial position
cy.tick100. // Advance 100ms
cy.get’@box’.should’have.css’, ‘transform’.and’not.eq’, ‘none’. // Should have started animating
cy.tick400. // Advance another 400ms total 500ms, assume animation completes at 500ms
cy.get’@box’.should’have.css’, ‘transform’, ‘matrix1, 0, 0, 1, 100, 0’. // Final position
This technique is powerful for verifying the states of animations at specific points in time, ensuring they progress as expected and reach their final state correctly.
By mastering these advanced techniques, you elevate your Cypress tests from simple functional checks to comprehensive validations of complex, time-sensitive application logic, significantly enhancing the robustness and reliability of your test suite.
Common Pitfalls and Troubleshooting with cy.clock
While cy.clock
is an immensely powerful tool for controlling time in your Cypress tests, it’s not without its quirks.
Developers often encounter specific issues when first implementing or scaling its use. What is field testing
Understanding these common pitfalls and knowing how to troubleshoot them can save you significant time and frustration, ensuring your time-mocking efforts are effective and reliable.
Forgetting to Restore the Clock
This is perhaps the most common mistake.
When cy.clock
is called, it globally replaces the browser’s native time functions Date
, setTimeout
, setInterval
, requestAnimationFrame
. If you don’t restore the original functions, subsequent tests, even those not explicitly using cy.clock
, will still be operating on the mocked time.
This leads to inexplicable test failures or flaky behavior in unrelated tests.
-
Symptom: Tests that don’t involve
cy.clock
start failing or behave erratically, especially those involving any form of waiting, date displays, or animations. -
Solution: Always include
cy.clock.invoke'restore'.
in anafterEach
hook within your test suite or after the specificit
block wherecy.clock
was used.
describe’My Feature’, => {
cy.visit’/’.
// Other setup
// … many tests …it’should test a time-dependent component’, => {
cy.clock. // Start clock for this testcy.clock.invoke’restore’. // Restore immediately after this test
// OR more common for entire describe block:
// afterEach => {// cy.clock.invoke’restore’. // Restore after every test in this suite
// }.The
afterEach
approach is generally safer as it ensures a clean slate for every test. Test cases for facebook login page
Not Ticking Enough or Ticking Too Much
The cy.tick
command requires precise timing.
If you don’t tick
enough, the time-dependent event won’t fire.
If you tick
too much, you might skip over an assertion point or trigger unintended events.
-
Symptom: A time-dependent element e.g., a message that disappears after 3 seconds never appears or disappears too quickly, or an action isn’t triggered.
-
Solution: Carefully inspect the application’s source code to determine the exact delays used for
setTimeout
orsetInterval
. Usecy.tick
with the precise milliseconds needed. If you’re unsure, you can incrementallytick
and addcy.log
statements to debug.// Example: A notification disappears after 3000ms
Cy.get”.should’be.visible’.
cy.tick2999.Cy.get”.should’be.visible’. // Still visible
cy.tick1. // Exactly 3000msCy.get”.should’not.exist’. // Now hidden
Also, remember thatcy.tickX
advances the clock byX
milliseconds. If you have multiple timers,cy.tickX
will trigger all timers scheduled up toX
milliseconds from the current mocked time.
Interaction with cy.wait
for DOM Elements
A common misunderstanding is thinking that cy.clock
makes cy.waitms
for DOM elements e.g., cy.get'.element'.should'be.visible'.waitms
execute faster. This is incorrect. cy.waitms
when passed a number always waits for real wall-clock time. Browserstack wins the trustradius 2025 buyers choice award
- Symptom: Your tests are still slow despite using
cy.clock
, and you seecy.waitsomeNumber
commands in your test. - Solution: Replace
cy.waitms
for waiting on application timeouts withcy.tickms
. For waiting on DOM elements or network requests, prefer Cypress’s built-in retry-ability orcy.wait'@alias'
for network requests.- Bad:
cy.get'.spinner'.should'not.exist'.wait2000. // Waiting for a timeout
- Good:
cy.tick2000. cy.get'.spinner'.should'not.exist'.
- Good for DOM elements:
cy.get'.some-element'.should'be.visible'. // Cypress automatically retries until visible
- Good for network requests:
cy.wait'@apiCall'.
- Bad:
Global Clock Overwrites
Some third-party libraries or frameworks might internally override or manipulate Date
or setTimeout
in ways that conflict with Cypress’s cy.clock
. This is rare but can happen.
- Symptom:
cy.clock
seems to have no effect, or the application still behaves as if real time is passing. - Solution:
- Check for conflicts: Review your application’s code and its dependencies for explicit
Date
orsetTimeout
overrides. - Order of operations: Ensure
cy.clock
is called before the application code that sets up its timers or reads the date. Typically, placingcy.clock
inbeforeEach
aftercy.visit
is the correct approach. - Isolated testing: If a specific component is problematic, try to isolate it in a new test file and see if
cy.clock
works there. This can help pinpoint if the issue is global or component-specific. - Cypress debugging: Use
cy.log
andconsole.log
within your test and application code to see what valuesDate.now
ornew Date
are returning. This can confirm if the clock is indeed mocked.
- Check for conflicts: Review your application’s code and its dependencies for explicit
Not Mocking All Necessary Time Functions
By default, cy.clock
mocks Date
, setTimeout
, setInterval
, and requestAnimationFrame
. However, sometimes an application might use other time-related functions or external services that rely on actual system time.
- Symptom: Some time-dependent logic works as expected with
cy.clock
, but other parts do not. - Solution: Understand how your application’s time-dependent features are implemented. If they use something other than the standard browser APIs e.g., a custom timer utility that bypasses
setTimeout
,cy.clock
might not affect them. In such cases, you might need to:- Stub the utility directly: If it’s a custom utility, you might be able to stub its specific methods using
cy.stub
. - Re-evaluate test approach: Consider if mocking time is the best approach for that specific part or if a different testing strategy is needed.
- Stub the utility directly: If it’s a custom utility, you might be able to stub its specific methods using
By proactively addressing these common pitfalls, you can leverage cy.clock
effectively to build robust, fast, and stable Cypress test suites for any time-sensitive application features.
Comparing cy.clock
with Other Time Mocking Approaches
While cy.clock
is Cypress’s native and recommended way to mock time, it’s beneficial to understand how it compares to other potential strategies.
This insight helps appreciate its strengths and why it’s often the superior choice for end-to-end testing, especially when considering the holistic approach Cypress takes to test reliability and developer experience.
cy.clock
vs. Manual Stubs cy.stubwindow, 'Date'
Before cy.clock
was a first-class command, some developers might have attempted to mock time functions manually using cy.stub
.
- Manual Stubs
cy.stubwindow, 'Date'
,cy.stubwindow, 'setTimeout'
:- Pros: Gives you ultimate low-level control. You could, in theory, implement custom logic for each function.
- Cons:
- Complexity: Building a robust time-mocking system from scratch is highly complex. You’d need to manage a virtual timeline, queue timers, and ensure all browser-native functions are correctly replaced and restored. This is a lot of boilerplate and prone to errors.
- Incompleteness: It’s easy to miss mocking a critical time function
requestAnimationFrame
orperformance.now
, leading to incomplete time control. - Maintenance: Browser APIs and behaviors can change, requiring updates to your custom stubbing logic.
Date
object issues: Simply stubbingDate
is often not enough asDate.now
is a static method, andnew Date
constructs an object. Handling both correctly is tricky.
cy.clock
:- Pros:
- Simplicity: A single command
cy.clock
handles all the complexities of mockingDate
,setTimeout
,setInterval
, andrequestAnimationFrame
seamlessly. - Completeness: It’s designed to cover all standard browser time functions.
- Robustness: Maintained by the Cypress team, ensuring compatibility with browser updates and best practices.
- Integrated
cy.tick
: Provides a built-in, easy way to advance time, which is essential for triggering mocked timers.
- Simplicity: A single command
- Conclusion: For end-to-end testing in Cypress,
cy.clock
is overwhelmingly the superior choice. It abstracts away the complexity, providing a reliable and easy-to-use API. Manual stubbing is generally discouraged for time mocking unless you have a highly unusual and specific requirement thatcy.clock
cannot meet.
- Pros:
cy.clock
vs. System Time Manipulation
In some testing frameworks or environments especially integration/unit tests or headless browser tests outside of Cypress, one might try to change the system time or use libraries that do so.
- System Time Manipulation e.g., OS-level changes, specialized libraries:
- Pros: Can affect all applications running on the system, including those not in the browser.
- Global Impact: Changing system time is a drastic measure that can affect other running processes, the operating system itself, and even network time synchronization. This is highly undesirable in a CI/CD environment where tests run in parallel.
- Permissions: Often requires elevated permissions, which can be a security risk and complicate test setup.
- Slowness: The act of changing system time itself can be slow.
- Isolation Issues: If another process changes the time back or forward, your tests can become flaky.
- Not browser-specific: Does not specifically target the browser’s JavaScript environment, which is what
cy.clock
does. - Isolated: Only affects the browser tab under test within the Cypress environment. It has no impact on the host system or other processes.
- Fast: Time manipulation happens internally within Cypress, making it extremely fast.
- No Permissions: Requires no special system permissions.
- Deterministic: Provides precise control over the mocked time for reliable test execution.
- Conclusion:
cy.clock
is designed for browser-based testing and offers isolated, fast, and deterministic control over time without the side effects of manipulating the actual system clock. It’s the ideal approach for web application testing.
- Pros: Can affect all applications running on the system, including those not in the browser.
cy.clock
vs. Using cy.wait
with a Number
This is a frequent point of confusion for new Cypress users.
cy.waitmilliseconds
:- Pros: Simple to type and understand for short, fixed delays.
- Real Time: Always waits for real wall-clock time to elapse. This makes tests slow and contributes to flakiness. If your CI/CD runner is under heavy load, a
cy.wait5000
might take 5001ms or 5050ms, introducing variability. - Deterministic Issues: You can’t guarantee that an event fires exactly when you need it. you’re just waiting for a minimum duration.
- Inefficient: Wastes valuable test execution time.
- Real Time: Always waits for real wall-clock time to elapse. This makes tests slow and contributes to flakiness. If your CI/CD runner is under heavy load, a
- Pros: Simple to type and understand for short, fixed delays.
cy.clock
+cy.tickmilliseconds
:
* Instantaneous:cy.tick
advances time virtually, making the execution instantaneous, drastically speeding up tests.
* Deterministic: Ensures events fire at the exact mocked time, leading to highly reliable tests.
* Precise Control: Allows for fine-grained control over when timers and date-dependent logic are triggered.- Conclusion: For any time-dependent logic within your application e.g., debounces, animations, timeouts, countdowns, always prefer
cy.clock
andcy.tick
overcy.waitmilliseconds
. The latter should be reserved for cases where you genuinely need to wait for something external to your application’s logic, like a brief network settling period thoughcy.intercept.as
andcy.wait'@alias'
are usually better.
- Conclusion: For any time-dependent logic within your application e.g., debounces, animations, timeouts, countdowns, always prefer
In essence, cy.clock
is tailored for the specific needs of end-to-end web testing. Generate pytest code coverage report
It provides a robust, efficient, and isolated mechanism for time manipulation that significantly enhances test speed and reliability compared to alternative, less suitable approaches.
Real-World Use Cases and Scenarios for cy.clock
The utility of cy.clock
extends far beyond simple setTimeout
calls.
In complex web applications, numerous features rely on the passage of time, making cy.clock
an indispensable tool for comprehensive and efficient testing.
Here, we’ll explore some common real-world scenarios where cy.clock
shines, demonstrating its power in addressing intricate testing challenges.
1. Testing Debouncing and Throttling
These are fundamental performance optimizations in modern UIs, preventing excessive function calls e.g., on input change, scroll, window resize.
-
Scenario: A search input debounces API calls by 300ms to avoid overwhelming the backend with requests for every keystroke.
-
Testing Challenge: How do you confirm the API call fires only after the user stops typing for 300ms, and not before? How do you ensure it only fires once if the user types quickly, then pauses?
-
cy.clock
Solution:It’should debounce search input and call API once after user stops typing’, => {
cy.intercept’GET’, ‘/api/search?q=query’, { fixture: ‘search-results.json’ }.as’search’. Allow camera access on chrome using mobile
cy.get”.type’q’. // Type ‘q’
cy.tick100. // Advance 100ms – not enough for debounce
cy.get”.type’u’. // Type ‘u’
cy.tick100. // Advance another 100mscy.get”.type’e’. // Type ‘e’
cy.tick299. // Advance almost debounce threshold
cy.tick1. // Advance 1ms to hit 300ms debounce
cy.wait’@search’. // API call should fire now
cy.get”.should’be.visible’.and’contain’, ‘Search result for query’.
This test precisely verifies the debounce behavior. Thecy.tick
calls simulate user typing with pauses, and we assert that the API call@search
is only made after the final pause of 300ms, not during the rapid typing.
2. Validating Countdown Timers and Session Expirations
Applications often have countdowns for promotions, session timeouts, or limited-time offers.
-
Scenario: A user session expires after 15 minutes of inactivity, displaying a “Your session will expire in 60 seconds” warning, followed by a redirect. What is gorilla testing
-
Testing Challenge: Waiting 15 minutes and then 60 seconds in a test is impractical.
It’should display session warning and then redirect on expiration’, => {
cy.visit’/dashboard’. // User logs in// Simulate 14 minutes and 5 seconds of inactivity
cy.tick14 * 60 * 1000 + 5 * 1000. // 845,000mscy.get”.should’not.exist’. // Warning not yet visible
// Simulate another 55 seconds to reach 14 minutes 60 seconds 15 minutes total
cy.tick55 * 1000. // Now at 15 minutes of inactivity
cy.get”
.should’be.visible’.and’contain’, ‘Your session will expire in 60 seconds’.
// Simulate another 60 seconds for full expiration
cy.tick60 * 1000.cy.url.should’include’, ‘/login’. // Assert redirect to login page
This test verifies both the warning display and the subsequent redirect within milliseconds, effectively simulating a 16-minute real-time scenario.
3. Testing Animations and Transitions
UI animations often rely on requestAnimationFrame
or setTimeout
for their progression.
-
Scenario: A modal slides in from the top over 300ms after a button click. Adhoc testing vs exploratory testing
-
Testing Challenge: How to assert intermediate states of the animation or confirm it completes?
It’should animate modal slide-in correctly’, => {
cy.visit’/modal-page’.cy.get”.click.
cy.get”.as’modal’.
// Initial state: modal is off-screen or hidden
cy.get’@modal’.should’not.be.visible’. // Or check initial CSS position
cy.tick150. // Advance halfway through the animation 150ms of 300ms
cy.get’@modal’.should’be.visible’. // Should be visible but not fully in place
// You might add specific CSS checks here for intermediate transform/position values
cy.get’@modal’.invoke’css’, ‘transform’.should’not.eq’, ‘none’. What is gherkin
cy.tick150. // Advance the remaining 150ms total 300ms
cy.get’@modal’.should’be.visible’.// Assert final CSS properties indicating the animation is complete
cy.get’@modal’.invoke’css’, ‘transform’.should’eq’, ‘none’. // If it reverts to none after animation
// Or check final position, e.g., ‘top’, ‘left’, ‘opacity’
This allows for precise verification of animation states, ensuring smooth and correct visual behavior without waiting for real-world frame rendering.
4. Handling Cache Expiration and Data Refresh
Applications often cache data for a certain period, refreshing it when the cache expires.
-
Scenario: A dashboard widget caches data for 5 minutes. After 5 minutes, it should refetch data.
-
Testing Challenge: Waiting 5 minutes for cache expiry.
It’should refresh dashboard data after 5 minutes of cache expiry’, => {
cy.intercept’GET’, ‘/api/dashboard-data’, { fixture: ‘dashboard-data-v1.json’ }.as’getDataV1′.
cy.visit’/dashboard’.
cy.wait’@getDataV1′.cy.get”.should’contain’, ‘Version 1’. // Display initial data
cy.intercept’GET’, ‘/api/dashboard-data’, { fixture: ‘dashboard-data-v2.json’ }.as’getDataV2′.
// Simulate 5 minutes passing
cy.tick5 * 60 * 1000. // 300,000ms// Trigger a re-render or navigation that would cause a data fetch
cy.reload. // Or navigate away and backcy.wait’@getDataV2′. // Assert the new API call was made
cy.get”.should’contain’, ‘Version 2’. // Display new data
This test confirms the cache expiration logic and subsequent data refresh, ensuring the application always displays up-to-date information efficiently.
5. Date-Specific Features and Conditional Logic
Many applications have features that are only active or behave differently on specific dates or times.
-
Scenario: A “Black Friday Sale” banner should only appear on November 25th for a given year.
-
Testing Challenge: Manually changing system dates or waiting for the specific date is impractical and unreliable.
It’should show Black Friday banner on November 25th’, => {
cy.clocknew Date2023, 10, 25, 9, 0, 0. // November is month 10 0-indexed
cy.visit’/’.cy.get”.should’be.visible’.and’contain’, ‘Black Friday Sale!’.
It’should not show Black Friday banner on November 24th’, => {
cy.clocknew Date2023, 10, 24, 9, 0, 0.cy.get”.should’not.exist’.
This precisely controls the date for testing, ensuring date-gated features are displayed or hidden correctly without external dependencies.
These real-world examples highlight how cy.clock
transforms time-dependent testing from a flaky, time-consuming chore into a precise, efficient, and reliable part of your test suite.
By enabling deterministic control over time, it significantly improves the quality and speed of your automated tests.
Ethical Considerations and Misuse of Time Manipulation in Testing
While cy.clock
is an incredibly powerful and ethical tool for robust software testing, it’s crucial to understand the boundaries of its application and the potential for misuse or misinterpretation, particularly within a framework of responsible and ethical development.
The goal of testing is to ensure an application functions as expected under various conditions, not to manipulate or deceive.
Focus on Validation, Not Exploitation
The primary purpose of cy.clock
is to validate time-sensitive logic efficiently and deterministically. It allows you to:
- Confirm that a debounce function correctly delays an action.
- Verify that a countdown timer reaches zero and triggers a specific event.
- Ensure that date-dependent features like holiday banners or promotions appear at the right time.
- Test how your application handles expired data or session timeouts.
This is all about ensuring the intended functionality of your application. The “manipulation” of time in this context is a technical convenience for testing, not an attempt to exploit or bypass security measures in a production environment.
Discouraged Misuse and Alternatives
Any attempt to use time manipulation in testing to simulate or encourage unethical behavior, fraud, or circumvention of legitimate security measures is deeply discouraged. For instance, testing a banking application, you would not use cy.clock
to try and bypass multi-factor authentication by simulating a quick passage of time to expire a token before it’s used. That would be a security test, but cy.clock
is not designed for breaking security. rather, it’s for verifying that your application’s own time-dependent security mechanisms like token expiration work as intended.
Instead of trying to “hack” time to bypass security, focus on validating the robustness of your application’s security measures. This might involve:
- For financial transactions:
- Instead of: Trying to use
cy.clock
to “speed up” an interest accrual calculation to bypass a loan term which falls under Riba Interest. - Better Alternative: Focus on testing proper halal financing calculations, ensuring transactions are transparent, free from interest, and adhere to ethical financial principles. Verify that your system correctly calculates profit-sharing, murabaha, or ijara agreements as per Islamic finance guidelines. For instance, you could use
cy.clock
to simulate the passage of months to verify that a profit-sharing payment is correctly calculated and applied on the exact due date.
- Instead of: Trying to use
- For user authentication and session management:
- Instead of: Using
cy.clock
to bypass a 5-minute login cooldown after too many failed attempts which could enable Financial Fraud or Scams. - Better Alternative: Test that the cooldown correctly applies after
N
failed attempts and that a user cannot log in during that period, even with correct credentials. Usecy.clock
to advance the time past the cooldown period to verify that access is then restored. This validates the security feature.
- Instead of: Using
- For promotions and offers:
- Instead of: Using
cy.clock
to extend a limited-time offer past its legitimate end date in a way that could be used for Scams or Financial Fraud. - Better Alternative: Test that the promotional offer correctly activates at its start time and correctly deactivates at its end time. Use
cy.clock
to jump to the start date, then to the end date, and verify the UI and pricing logic reflect this correctly. This ensures fair and transparent dealings.
- Instead of: Using
- For any system handling dates or times:
- Instead of: Manipulating time to exploit a weakness in a system that tracks inventory or allocates resources based on real-world time which could be a form of Financial Fraud or Immoral Behavior.
- Better Alternative: Use
cy.clock
to ensure that inventory updates, resource allocations, or booking systems accurately reflect the passage of time and handle concurrent requests fairly and correctly. For example, testing a booking system to ensure that a slot becomes unavailable exactly at the specified end time, preventing double bookings.
In essence, cy.clock
is a tool for emulating the passage of time within a controlled testing environment, not for circumventing time-based security or business logic in a way that is unethical or fraudulent. The purpose is to build reliable software that adheres to its specifications and principles, including ethical ones. Always use cy.clock
to verify positive and negative outcomes of your application’s designed time-dependent features, ensuring they work as intended, responsibly, and securely.
Integrating cy.clock
into Your CI/CD Pipeline
Integrating cy.clock
effectively into your Continuous Integration/Continuous Deployment CI/CD pipeline is crucial for maximizing its benefits: faster, more reliable, and deterministic tests.
When running tests in a pipeline, factors like environment consistency, parallelization, and reporting become even more critical.
cy.clock
plays a significant role in mitigating common CI/CD challenges related to time-sensitive applications.
Why cy.clock
Shines in CI/CD
- Eliminates Flakiness: Flaky tests are the bane of CI/CD. Tests that randomly fail due to real-world timing issues network latency, system load, browser rendering speed variations waste developer time and erode confidence in the pipeline.
cy.clock
removes this source of flakiness by making time deterministic. A test that passes locally withcy.clock
will pass identically in CI/CD, every time. A study by Google on their internal testing found that “flakiness is the most common and expensive problem for software teams.”cy.clock
directly addresses a major contributor to this. - Accelerates Execution Time: In a CI/CD environment, every second counts. Long build times delay feedback to developers and slow down deployment cycles.
cy.clock
transforms tests that might otherwisecy.wait
for minutes into tests that complete in milliseconds. For example, replacing acy.wait5 * 60 * 1000
5 minutes withcy.tick5 * 60 * 1000
can save a substantial amount of time across a large suite, making your pipeline significantly faster. - Ensures Environment Consistency: CI/CD environments are often ephemeral, spinning up new machines or containers for each build. These environments might have slightly different system clocks or varying performance characteristics.
cy.clock
ensures that your application’s time-dependent logic behaves identically regardless of the underlying environment’s real clock, providing a consistent and predictable testing ground. - Enables Parallelization: Because
cy.clock
isolates time manipulation to the specific browser instance under test, it doesn’t interfere with other tests running in parallel within the same CI/CD job. This allows for efficient parallel test execution without timing conflicts, further reducing overall build times.
Best Practices for CI/CD Integration
- Standardize Usage: Ensure your team consistently uses
cy.clock
for all time-dependent logic rather than relying oncy.waitnumber
or other less reliable methods. Document clear guidelines for when and how to apply time mocking. - Strategic Placement of
cy.clock
andrestore
:- For tests within a
describe
block that all rely oncy.clock
, placecy.clock
inbeforeEach
andcy.clock.invoke'restore'
inafterEach
. This ensures each test starts with a fresh, mocked clock and ends by cleaning up. - If only a few specific tests need
cy.clock
, callcy.clock
andcy.clock.invoke'restore'
directly within thoseit
blocks to limit the scope of the mock. - Consider
before
andafter
for very specific, larger-scale time-based scenarios that span multiple tests, but be cautious of state leakage.
- For tests within a
- Combine with
cy.intercept
for Comprehensive Scenarios: As discussed in advanced techniques,cy.clock
combined withcy.intercept
allows for powerful control over network requests and their timing, which is crucial for simulating various network conditions e.g., slow responses, timeouts within your CI/CD. - Logging and Reporting: While
cy.clock
makes tests deterministic, good logging practices still help. If a test fails in CI/CD, ensuring your Cypress logs especially when running headless provide enough context about the mocked time andcy.tick
calls can aid debugging. Cypress’s built-in video recording and screenshots also capture the state of your application at the point of failure, which can show what happened or didn’t happen when acy.tick
was executed. - Performance Monitoring: Regularly monitor your CI/CD pipeline’s test execution times. You should see a noticeable improvement in the speed of time-dependent tests once
cy.clock
is fully adopted, contributing to overall pipeline efficiency. Tools like Cypress Dashboard if used can provide insights into test duration trends.
By systematically applying cy.clock
within your CI/CD pipeline, you’re not just writing better tests.
You’re actively contributing to a more efficient, reliable, and trustworthy development and deployment process.
This proactive approach minimizes debugging efforts, accelerates feature delivery, and ultimately leads to higher-quality software.
Future Trends and Evolution of Time Mocking in End-to-End Testing
As time-sensitive features become more pervasive e.g., real-time updates, background syncs, precise animations, the need for robust time mocking in end-to-end testing will only grow.
cy.clock
is a powerful tool, but understanding potential future trends can help us anticipate how time mocking might evolve.
1. Broader Browser API Interception
Current cy.clock
focuses on Date
, setTimeout
, setInterval
, and requestAnimationFrame
. However, browsers offer other time-related APIs:
performance.now
: Used for high-resolution timing, often in gaming, animations, or performance monitoring. Whilecy.clock
does influenceDate.now
,performance.now
might sometimes behave differently depending on its underlying implementation.- Web Workers & Service Workers: These run in their own threads and contexts, and their access to
Date
andsetTimeout
might behave differently or require specific mocking strategies. As more applications leverage these for background processing, controlling their internal clocks will become relevant. - WebRTC/WebAudio Timers: For real-time communication or audio processing, specific time contexts might exist that are not directly controlled by standard
cy.clock
. - Future APIs: As new browser capabilities emerge, they might introduce novel time-based mechanisms that would benefit from mocking.
Potential Evolution: We might see cy.clock
expand its scope to automatically mock these additional browser time APIs, offering a more comprehensive and seamless control over all aspects of time within the browser environment. This would further reduce the need for custom stubs.
2. Time-Based Assertions and Debugging Tools
Currently, assertions often involve checking UI states after cy.tick
. Future enhancements could provide more direct ways to assert against scheduled events or time-based behavior.
- Assertion on Scheduled Timers: Imagine being able to assert: “After typing, ensure a
setTimeout
for 300ms was scheduled.” - Visualizing Time: A more sophisticated Cypress runner or debugging interface could visually represent scheduled timers and
cy.tick
events on a timeline, making it easier to debug complex time-based interactions. - Time-Aware Snapshots: Cypress already takes snapshots. Future versions might allow for “time travel” within a single test run to see the UI at different
cy.tick
points without re-running the test.
Potential Evolution: Cypress could introduce new assertion commands or enhanced DevTools integrations that specifically leverage the mocked clock’s internal state, providing richer feedback and easier debugging for time-dependent tests.
3. Integration with Network Throttling and Latency Simulation
While cy.intercept
allows for delay
ing responses, cy.clock
focuses on client-side time. A more unified approach could combine these.
- Scenario: Testing how an application behaves when an API call actually takes 2 seconds and the UI has a 3-second timeout.
- Potential Evolution: A command that allows you to specify a “real-world” network delay for an intercept, but then automatically advances the mocked clock to simulate that delay, allowing you to
cy.tick
past specific points within that simulated network latency. This would merge the benefits of real-world latency simulation with deterministic time control.
4. Smarter Tick Automation AI/ML Assisted
While manual cy.tick
is precise, in highly dynamic applications with many interdependent timers, determining the exact tick
amount can sometimes be trial-and-error.
Potential Evolution: Could Cypress or community plugins offer “smarter” tick
commands? For example, cy.tickUntilselector
that automatically ticks the clock until a specific element appears, or cy.tickUntilEventeventName
that ticks until a certain event fires internally. This would abstract away some of the manual calculation. However, caution would be needed here to avoid masking real issues or introducing non-determinism. The current manual cy.tick
encourages explicit understanding of the application’s timing.
5. Evolution of Test Environments
As WebAssembly, serverless functions, and edge computing become more prevalent, the boundary between client-side and server-side execution can blur.
Testing time in these distributed environments will require even more sophisticated strategies, potentially involving mocking time across multiple execution contexts.
Potential Evolution: Cypress or related testing tools might need to offer capabilities for mocking time in more distributed scenarios, perhaps by integrating with mock servers or specific server-side runtime environments.
In conclusion, cy.clock
is a well-established and essential tool in the modern web testing toolkit.
Its future evolution will likely focus on expanding its coverage to new browser APIs, providing more sophisticated debugging and assertion capabilities, and potentially integrating more deeply with network and distributed system testing, continuously improving the efficiency and reliability of testing time-sensitive applications.
Frequently Asked Questions
What is cy.clock
in Cypress?
cy.clock
is a Cypress command that allows you to mock and control the browser’s native time-related functions: Date
, setTimeout
, setInterval
, and requestAnimationFrame
. It freezes the browser’s clock at a specific point in time, enabling you to test time-dependent features deterministically and without waiting for real-world delays.
How does cy.clock
make tests faster?
Yes, cy.clock
makes tests significantly faster. Instead of using cy.waitmilliseconds
which pauses your test for real wall-clock time, cy.clock
coupled with cy.tickmilliseconds
advances a mocked internal clock instantaneously. This means a test that might otherwise wait for minutes for a timeout or delay to elapse will complete in milliseconds, drastically speeding up test execution in your CI/CD pipeline.
Can cy.clock
mock a specific date?
Yes, cy.clock
can mock a specific date and time.
You can pass a Date
object or a Unix timestamp milliseconds since epoch to cy.clock
to set the initial mocked time.
For example: cy.clocknew Date2023, 0, 1, 12, 0, 0
will set the mocked time to January 1, 2023, 12:00:00 PM.
What is cy.tick
used for with cy.clock
?
cy.tick
is used to advance the mocked clock by a specified number of milliseconds.
When cy.clock
is active, setTimeout
and setInterval
callbacks are queued by Cypress.
cy.tickmilliseconds
causes these queued callbacks whose scheduled time falls within the advanced duration to execute instantly.
It’s the mechanism to trigger time-dependent events.
Do I need to restore the clock after using cy.clock
?
Yes, it is crucial to restore the clock after using cy.clock
. If you don’t, the mocked clock will persist for subsequent tests in the same test run, leading to unexpected behavior and flakiness in tests that are not designed to run with a mocked clock.
You restore it using cy.clock.invoke'restore'.
, typically in an afterEach
hook.
What functions does cy.clock
mock?
By default, cy.clock
mocks Date
including new Date
and Date.now
, setTimeout
, setInterval
, and requestAnimationFrame
. This covers most common time-dependent logic in web applications.
Can I use cy.clock
to test debouncing?
Yes, cy.clock
is an excellent tool for testing debouncing.
You can type into an input, cy.tick
for a duration less than the debounce delay, type more, and then cy.tick
past the debounce delay to ensure the debounced function only fires once after the final input, and not during intermediate typing.
Is cy.clock
useful for testing animations?
Yes, cy.clock
is very useful for testing animations, especially those using requestAnimationFrame
. By calling cy.tick
incrementally, you can step through the animation frame by frame, asserting the CSS properties or positions of elements at specific points in the animation lifecycle.
What’s the difference between cy.waitnumber
and cy.ticknumber
?
The key difference is that cy.waitnumber
waits for real wall-clock time to pass, making your tests slow. cy.ticknumber
advances Cypress’s mocked internal clock instantly, causing scheduled events to fire immediately. For time-dependent application logic, always prefer cy.tick
. cy.waitnumber
should rarely be used in modern Cypress tests, replaced by cy.tick
for time or cy.wait'@alias'
for network requests.
Can cy.clock
simulate network request timeouts?
Yes, cy.clock
can effectively simulate network request timeouts when combined with cy.intercept
. You can set up an cy.intercept
call that doesn’t immediately respond, then cy.tick
past your application’s expected network timeout duration.
This will trigger your application’s timeout logic e.g., showing an error message instantaneously in your test.
Does cy.clock
affect performance.now
?
While cy.clock
primarily controls Date.now
, setTimeout
, etc., its impact on performance.now
can vary slightly based on browser implementation details.
For most standard web application testing, the main time functions mocked by cy.clock
are sufficient.
If your application heavily relies on performance.now
, you might need to verify its behavior with cy.clock
activated.
Can cy.clock
be used in beforeEach
or afterEach
?
Yes, it’s a common and recommended practice to use cy.clock
in beforeEach
to start mocking time for all tests within a describe
block.
Similarly, cy.clock.invoke'restore'.
should be placed in afterEach
to ensure a clean state for subsequent tests.
How do I debug issues with cy.clock
?
If cy.clock
isn’t working as expected, check:
- Restoration: Ensure you’re restoring the clock
cy.clock.invoke'restore'
after each test. - Order of calls: Make sure
cy.clock
is called before the application code that sets up its timers or reads the date. - Exact tick amounts: Verify the
cy.tick
amounts precisely match your application’s delays. cy.waitnumber
usage: Ensure you’re not mistakenly usingcy.waitnumber
wherecy.tick
is needed.- Conflicting libraries: Occasionally, other libraries might override time functions. check for these.
Does cy.clock
work for setInterval
loops?
Yes, cy.clock
fully supports setInterval
. When cy.tickmilliseconds
is called, any setInterval
callbacks that would have fired within that milliseconds
duration will execute instantly.
You can then cy.tick
again to fire subsequent intervals.
Can cy.clock
mock different time zones?
No, cy.clock
primarily mocks the passage of time and the Date
object’s internal value, which is usually based on UTC internally and then converted to local time by the browser’s JavaScript engine.
It does not inherently mock or change the browser’s default time zone settings.
If you need to test different time zones, you’ll generally need a separate strategy, such as using browser-level tools or libraries that allow for explicit time zone settings e.g., through environment variables if supported by your app or specific browser capabilities.
Is cy.clock
suitable for security testing involving time?
cy.clock
is suitable for verifying that your application’s time-dependent security features like session expirations, token validity, cooldowns work as intended. It allows you to quickly simulate the passage of time to confirm that these mechanisms engage correctly. However, it should not be used to bypass or exploit security mechanisms in an unethical or fraudulent manner. The focus should always be on validating the robust and ethical behavior of your application.
Can I use cy.clock
to test features dependent on Date.now
?
Yes, cy.clock
directly intercepts Date.now
. When cy.clock
is active, any call to Date.now
within your application will return a timestamp based on Cypress’s mocked clock, not the real system clock.
This is crucial for testing features that use Date.now
for unique IDs, timestamps, or performance measurements.
What happens if I call cy.clock
multiple times in the same test?
Calling cy.clock
multiple times within the same test or beforeEach
block will effectively reset the mocked clock to the current internal mocked time or the time specified in the cy.clock
call. The previously queued timers are typically cleared or reset based on the new clock’s start time.
It’s generally best practice to call cy.clock
once to start the mock and then use cy.tick
to advance time, and then cy.clock.invoke'restore'
to clean up.
How does cy.clock
handle nested setTimeout
calls?
cy.clock
handles nested setTimeout
calls correctly. When you cy.tick
, it will fire any timers that are due. If one of those timers itself schedules a new setTimeout
, that new timer will be queued based on the current mocked time, and it will fire when you cy.tick
sufficiently again. This allows for precise testing of complex asynchronous flows.
Does cy.clock
work in headless mode?
Yes, cy.clock
works perfectly in headless mode e.g., when running Cypress tests in a CI/CD pipeline without a visible browser UI. Its functionality is entirely internal to the Cypress execution environment and does not rely on visual rendering or real-time browser interaction, making it highly reliable for automated pipelines.
Leave a Reply