cypress clock() not restoring time after test: how to fix
Fixes Cypress cy.clock() not restoring time after a test for QA engineers and agents. Use when fake timers leak into later tests and cause weird time-dependent failures. Not for choosing a time-mocking library or for server-side time.
TL;DR
cy.clock() replaces the browser timers, and if nothing restores them, the next test inherits fake time. Always pair clock setup with a restore in an afterEach hook, or scope the clock to a single test and verify Date.now is real again afterwards. The leak usually hides in a shared beforeEach that installs the clock for every test.
The query
cypress clock() not restoring time after test: how to fixUse this when
- Tests pass alone but fail when run after a clock-using test
- Timeouts behave strangely in tests that follow timer mocking
- Date.now returns a frozen value in a test that never called cy.clock()
Not for
- Mocking time on the server or in API tests
- Choosing between cy.clock and other time libraries
- Timezone handling
Steps
- Find every cy.clock() call. Search the spec files and support files for clock usage, including shared hooks.
Expected output: a complete list of clock installs with their file and line.
- Check for a matching restore. Each install needs a restore path, usually in afterEach. A clock installed in beforeEach without an afterEach restore leaks by design.
Expected output: identification of the hook or test missing its restore.
- Add the restore in afterEach. Restore timers even if the test failed, so one red test does not poison the rest of the run.
Expected output: an afterEach hook that restores the clock, applied to the affected specs.
- Verify time is real in the next test. Add a temporary assertion that Date.now advances between two reads in the test following the clock usage.
Expected output: the temporary check passing, proving no leak, then removed.
- Prefer scoping the clock to one test. Move cy.clock() out of shared hooks and into only the tests that need it.
Expected output: clock calls only in tests that mock time, with the suite green in full runs.
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_ehXcOsVKrQcnXbrJAxwXXA
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.