如何使用 cy.clock() 获取当前日期

Zom*_*Pie 4 javascript cypress

我如何使用 cy.clock() 获取 dd/mm/yyyy 格式的日期并将日期放入文本字​​段中。我见过大多数示例都获取时间戳,但我不需要时间。只需要当前日期。

我不想在这里使用自定义命令。谢谢

Fod*_*ody 7

cy.clock()是关于控制应用程序的感知日期。

例子来看,

让测试在某个日期运行

const now = new Date(2017, 3, 14).getTime() // April 14, 2017 timestamp

cy.clock(now)
cy.visit('/index.html')
cy.get('#date').contains('2017-04-14')  
Run Code Online (Sandbox Code Playgroud)

在具有特定格式的字段中输入内容

如果您想要.type()特定的日期字符串,请使用.toLocaleDateString()

const d = new Date()  // current date
// or
const d = new Date(2017, 3, 14)  // specific date

cy.get('input').type(d.toLocaleDateString('en-GB'))  // type in as 'dd/mm/yyyy'
Run Code Online (Sandbox Code Playgroud)

将两者结合起来,例如测试验证

// Set clock to a specific date
const now = new Date(2017, 3, 14).getTime() // April 14, 2017 timestamp
cy.clock(now)
cy.visit('/index.html')

// Type in an earlier date
const d = new Date(2017, 3, 13)
cy.get('input').type(d.toLocaleDateString('en-GB'))
  .blur()    // fire validation
  .should('contain', 'Error: Date entered must be a future date')
Run Code Online (Sandbox Code Playgroud)


Ala*_*Das 5

您可以用来day.js获取当前日期并相应地设置其格式。

const dayjs = require('dayjs')

//In test
cy.log(dayjs().format('DD/MM/YYYY'))  //Prints todays date 30/09/2021
cy.get('textfield').type(dayjs().format('DD/MM/YYYY')) //input today's date in DD/MM/YYYY format
Run Code Online (Sandbox Code Playgroud)