如何将Cypress中newDate转为YYYY-MM-DD格式以匹配输入框值?
解决Cypress日期输入框格式匹配问题
你遇到的问题是因为new Date()生成的默认日期字符串格式和输入框的YYYY-MM-DD不匹配,导致断言失败。只需要把日期格式化为指定的YYYY-MM-DD格式即可,下面提供两种简单的修改方式:
方法一:手动拼接格式化日期
通过Date对象的方法获取年、月、日,手动拼接成目标格式(注意月份是从0开始计数,需要加1,并且用padStart(2, '0')补零保证两位数):
cy.window().then((win) => { const currentDate = new Date(win.Date()); const year = currentDate.getFullYear(); const month = String(currentDate.getMonth() + 1).padStart(2, '0'); const day = String(currentDate.getDate()).padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; cy.get('#datefrom').should('be.visible').and('have.value', formattedDate); });
方法二:利用toISOString()快速截取
toISOString()方法会返回类似2023-04-05T15:50:37.000Z的字符串,直接截取前10位就能得到YYYY-MM-DD格式:
cy.window().then((win) => { const formattedDate = new Date(win.Date()).toISOString().slice(0, 10); cy.get('#datefrom').should('be.visible').and('have.value', formattedDate); });
这两种方式都能生成和输入框一致的日期格式,解决断言报错的问题。
内容的提问来源于stack exchange,提问作者Michelle Murray
相关产品推荐
相关产品推荐

