乐闻世界logo
搜索文章和话题

How to get current date using cy.clock in cypress

1个答案

1

In Cypress, using cy.clock() is primarily for controlling time and date by overriding JavaScript's date and time functions in tests. This is very useful for simulating or testing events triggered by specific dates or times. cy.clock() locks all time-related functions, ensuring that the test time remains fixed at the set point regardless of real-time progression.

How to Use cy.clock() to Get the Current Date

  1. Initialize the Clock: In your tests, you first need to initialize the clock using cy.clock(). This is typically done at the beginning of the test. If no parameters are passed, it locks the time to January 1, 1970 UTC.
javascript
cy.clock()
  1. Set Specific Time: You can set cy.clock() parameters by passing a timestamp or a Date object to lock to a specific date and time. For example, if you want to set the time to January 1, 2023:
javascript
const now = new Date(2023, 0, 1).getTime() // Months are zero-based, so 0 represents January cy.clock(now)
  1. Use Time Functions: Once cy.clock() is set, any time functions such as new Date(), setTimeout(), setInterval(), etc., will use the locked time instead of the current real time.
javascript
cy.log(new Date().toString()) // This outputs "Sun Jan 01 2023 00:00:00 GMT+0000 (Coordinated Universal Time)"

Example: Testing Element Display at Specific Time

Suppose you are testing a website that displays a special message on New Year's Day. You can use cy.clock() to simulate this scenario:

javascript
describe('New Year Celebration Banner Test', function() { it('should display the New Year banner on January 1, 2023', function() { cy.visit('/home') const newYearTime = new Date(2023, 0, 1).getTime() cy.clock(newYearTime) cy.reload() cy.get('.new-year-banner').should('be.visible') }) })

In this test, we set the time to January 1, 2023, then reload the page, and check if the New Year banner is displayed. This approach is ideal for testing features triggered by specific times.

2024年6月29日 12:07 回复

你的答案