clock | Cypress Documentation (2024)

cy.clock() overrides native global functions related to time allowing them tobe controlled synchronously via cy.tick() or the yieldedclock object. This includes controlling:

  • setTimeout
  • clearTimeout
  • setInterval
  • clearInterval
  • Date Objects

The clock starts at the unix epoch (timestamp of 0). This means that when youinstantiate new Date in your application, it will have a time ofJanuary 1st, 1970.

Syntax

cy.clock()cy.clock(now)cy.clock(now, functionNames)cy.clock(options)cy.clock(now, options)cy.clock(now, functionNames, options)

Usage

Correct Usage

cy.clock()

Arguments

now (number)

A timestamp specifying where the clock should start.

functionNames (Array)

Name of native functions that clock should override.

options (Object)

Pass in an options object to change the default behavior of cy.clock().

OptionDefaultDescription
logtrueDisplays the command in the Command log

Yields

cy.clock() yields a clock object with the following methods:

You can also access the clock object via this.clock in a.then() callback.

Examples

No Args

Create a clock and use it to trigger a setInterval

// your app codelet seconds = 0setInterval(() => { $('#seconds-elapsed').text(++seconds + ' seconds')}, 1000)
cy.clock()cy.visit('/index.html')cy.tick(1000)cy.get('#seconds-elapsed').should('have.text', '1 seconds')cy.tick(1000)cy.get('#seconds-elapsed').should('have.text', '2 seconds')

Access the clock object to synchronously move time

In most cases, it's easier to use cy.tick() to movetime, but you can also use the clock object yielded by cy.clock().

cy.clock().then((clock) => { clock.tick(1000)})

You can call cy.clock() again for this purpose later in a chain if necessary.

cy.clock()cy.get('input').type('Jane Lane')cy.clock().then((clock) => { clock.tick(1000)})

The clock object is also available via this.clock in any.then() callback.

cy.clock()cy.get('form').then(($form) => { this.clock.tick(1000) // do something with $form ...})

Access the clock object to restore native functions

In general, it should not be necessary to manually restore the native functionsthat cy.clock() overrides since this is done automatically between tests. Butif you need to, the clock object yield has a .restore() method.

cy.clock().then((clock) => { clock.restore()})

Or via this.clock:

cy.clock()cy.get('.timer').then(($timer) => { this.clock.restore() // do something with $timer ...})

Now

Specify a now timestamp

const now = new Date(2021, 3, 14) // month is 0-indexedcy.clock(now)cy.visit('/index.html')cy.get('#date').should('have.value', '04/14/2021')
const now = new Date(2021, 3, 14) // month is 0-indexedcy.clock(now)cy.mount(<DatePicker id="date" />)cy.get('#date').should('have.value', '04/14/2021')

Function names

Specify which functions to override

This example below will only override setTimeout and clearTimeout and leavethe other time-related functions as they are.

cy.clock(null, ['setTimeout', 'clearTimeout'])

Note that you must specify Date in order to override the current datetime. Theexample below affects the current datetime without affecting scheduled timers.

cy.clock(Date.UTC(2018, 10, 30), ['Date'])

Using cy.clock() with cy.tick()

Check out our example recipe testing spying, stubbing and time.

Restore clock

You can restore the clock and allow your application to resume normally withoutmanipulating native global functions related to time. This is automaticallycalled between tests.

cy.clock()cy.visit('http://localhost:3333')cy.get('#search').type('Acme Company')cy.tick(1000)// more test code here// restore the clockcy.clock().then((clock) => { clock.restore()})// more test code here

You could also restore by using .invoke() to invoke therestore function.

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

Change current system time

Here we test that a timer still looks good if it has run for an hour, withouttriggering an hours worth of setInterval or requestAnimationFrame timers andoverloading our CPU.

cy.clock(0)cy.visit('http://localhost:3333')cy.clock().then((clock) => { clock.setSystemTime(60 * 60 * 1000 - 60); // setSystemTime doesn't trigger any timers, so we run the last frame // with tick to trigger a callback to update the timer. clock.tick(60);})cy.get('#timer').should(...) // assert that it fits within the screen etc.// more test code here

You could also change the system time by using .invoke()to invoke the setSystemTime function.

cy.clock().invoke('setSystemTime', 60 * 60 * 1000)

Notes

iframes

iframes not supported

Note that cy.clock() only applies to the top window on a web page. It willnot override the time functions of any iframe embedded on the page.

Behavior

clock behavior before cy.mount()

Using the cy.mount() command in a Cypress ComponentTest will render your component but does not affect the behavior of the page orwindow object. This means you can mount directly after calling cy.clock() totest the component against any changes you've made to the yielded clock object.

clock behavior before cy.visit()

If you call cy.clock() before visiting a page withcy.visit(), the page's native global functions will beoverridden on window load, before any of your app code runs. So even ifsetTimeout, for example, is called on page load, it can still be controlledvia cy.tick(). This also applies if, during the courseof a test, the page under test is reloaded or changed.

Rules

Requirements

  • cy.clock() requires being chained off of cy.

Assertions

  • cy.clock() is a utility command.
  • cy.clock() will not runassertions. Assertions will pass through as if this command did notexist.

Timeouts

  • cy.clock() cannot time out.

Command Log

Create a clock and tick it 1 second

cy.clock()cy.tick(1000)

The command above will display in the Command Log as:

clock | Cypress Documentation (1)

When clicking on the clock command within the command log, the console outputsthe following:

clock | Cypress Documentation (2)

History

VersionChanges
10.7.0Added setSystemTime to yielded clock object

See also

  • cy.spy()
  • cy.stub()
  • cy.tick()
  • Guide: Stubs, Spies and Clocks
  • Recipe: Stubbing, Spying
clock | Cypress Documentation (2024)

FAQs

What is the difference between Cy stub and Cy spy? ›

Difference between cy.

stub() is that cy. spy() does not replace the method, it only wraps it. So, while invocations are recorded, the original method is still called. This can be very useful when testing methods on native browser objects.

What is the Cypress test? ›

Cypress is a next generation front end testing tool built for the modern web. We address the key pain points developers and QA engineers face when testing modern applications. We make it possible to: Set up tests. Write tests.

What is a cy clock? ›

cy. clock() overrides native global functions related to time allowing them to be controlled synchronously via cy. tick() or the yielded clock object. This includes controlling: setTimeout.

What is a cy stub? ›

cy. stub() is a utility function, and is not a Cypress command, query or assertion. It is not retryable, chainable, or timeout-able. Note: .stub() assumes you are already familiar with our guide: Stubs, Spies, and Clocks.

What is a mock vs stub? ›

What is the main difference between a stub and a mock? Stubs provide predefined responses to calls and focus on outcomes, while mocks record and validate interactions between the actual database objects, thus concentrating on behavior.

What is the difference between a stub and a spy? ›

While stubs provide predefined responses, spies are designed to focus on observing and capturing interactions. It can capture and record the order in which methods are called. Spying enables the capture of values during interactions, allowing to assert on them later.

What is a Scott clock? ›

This clock is based on the 'Ever Ready electrically propelled clocks' which were manufactured at the beginning of the 20th century to the design of Herbert Scott in the early 1900s. A unique feature is the motion of the pendulum which swings backwards and forwards instead of from side to side.

What does a cy wrap do? ›

Whenever you're using a child command you likely want to use cy. wrap() on the subject. Wrapping it enables you to immediately use more Cypress commands on that subject.

What is a clock in coding? ›

The clock() function in C returns the approximate processor time that is consumed by the program which is the number of clock ticks used by the program since the program started.

What is a coding stub? ›

A method stub or simply stub in software development is a piece of code used to stand in for some other programming functionality. A stub may simulate the behavior of existing code (such as a procedure on a remote machine, such methods are often called mocks) or be a temporary substitute for yet-to-be-developed code.

How does stub work? ›

A stub interface simulates an actual object by using a few methods. It's an object with pre-existing data that delivers a constant value regardless of input. You can utilize it when the test suite is simple and hard-coded values aren't an issue. Both developers and testers also use it.

Why is stub used? ›

Stubs are small pieces of code that take the place of another component during testing. The benefit of using a stub is that it returns canned results and answers, making the test easier to write. You can run your tests even if the other component isn't working yet.

What is the difference between mock stub and spy? ›

When using mock objects, the default behavior of methods (when not stubbed) is do nothing (performs nothing.) When using spy objects, the default behavior of the methods (when not stubbed) is the real method behavior. In our previous tutorials, we have discussed some examples of stubbing, mocking, and spying.

What is the use of stub in Cypress? ›

Stubs​ A stub is a way to modify a function and delegate control over its behavior to you (the programmer). A stub is most commonly used in a unit test but is still useful during some integration/e2e tests. You generally stub a function when it has side effects you are trying to control.

What is stub vs mock vs spy jest? ›

While a Stub simulates real objects with the minimum methods needed for a test, Mock objects are used to check if the correct techniques and paths are applied to the objects. Additionally, Mock is very useful when we have an extensive test suite, and each test requires a unique data set.

What is Spy vs mock vs stub Swift? ›

Spies are stubs that also record some information based on how they were called. One form of this might be an email service that records how many messages it was sent. Mocks are pre-programmed with expectations which form a specification of the calls they are expected to receive.

Top Articles
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 6654

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.