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



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

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

您可以使用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

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')  

以特定格式键入字段

如果要.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'

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

// 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')

我偶然发现了这个线程,因为我正在寻找一种方法来检索";当前日期";在测试中。所以,对于其他正在寻找这个的人来说:在另一个帖子中,我找到了答案:

cy.window().then((win) => {
const newDate = new Date(win.Date());
// do something usefull with the date
}

最新更新