如何在Cypress JS测试中对比UI日期与MySQL数据库存储日期?
Cypress日期对比断言失败问题
我在Cypress测试中尝试对比MySQL数据库获取的日期与UI显示的日期,断言代码如下:
cy.compareDates(result[0].publishdate, companyDetails.publishedDate())
- 数据库返回的
result[0].publishdate值为2022-02-14 16:45:37(作为预期日期) - UI元素方法
companyDetails.publishedDate()返回的文本是14-Feb-2022(作为实际日期)
自定义的compareDates命令代码如下:
Cypress.Commands.add('compareDates', (expectedDate, actualDate) => { actualDate.then(date => { const reformattedDate = new Date(date.text()) cy.log('reformat: ' + reformattedDate) cy.log('ISO string: ' + reformattedDate.toISOString().split('T')[0]) // expect(reformattedDate.toISOString().split('T')[0]).to.equal(expectedDate.split('T')[0]) }) })
取消注释断言后测试失败,日志显示:
Reformatted Date: Fri Sep 11 2015 00:00:00 GMT+0100 (British Summer Time)
ISO string: 2015-09-10
奇怪的是,该命令对部分日期能正常工作,比如:
Reformatted Date: Wed Feb 28 2007 00:00:00 GMT+0000 (Greenwich Mean Time)
ISO string: 2007-02-28
问题原因
原生new Date()构造函数对14-Feb-2022这类非标准日期格式的解析行为不稳定,不同运行环境(浏览器、Node.js)的解析逻辑存在差异,导致解析出错误的日期值。此外,直接使用toISOString()还可能因时区偏移问题,导致日期字符串与预期不符。
解决方法
方案1:手动解析日期格式
手动拆分UI返回的日期字符串,构建正确的日期对象(使用UTC时区避免偏移问题):
Cypress.Commands.add('compareDates', (expectedDate, actualDate) => { actualDate.then(date => { const dateText = date.text().trim(); const [day, monthStr, year] = dateText.split('-'); // 月份缩写映射为数字(0-11对应1-12月) const monthMap = { 'Jan': 0, 'Feb': 1, 'Mar': 2, 'Apr': 3, 'May': 4, 'Jun': 5, 'Jul': 6, 'Aug': 7, 'Sep': 8, 'Oct': 9, 'Nov': 10, 'Dec': 11 }; // 用UTC时区创建日期,避免本地时区偏移 const reformattedDate = new Date(Date.UTC(year, monthMap[monthStr], day)); const actualIsoDate = reformattedDate.toISOString().split('T')[0]; // 从数据库日期中提取日期部分 const expectedIsoDate = expectedDate.split(' ')[0]; cy.log('reformat: ' + reformattedDate) cy.log('ISO string: ' + actualIsoDate) expect(actualIsoDate).to.equal(expectedIsoDate); }) })
方案2:使用dayjs库处理日期(更简洁可靠)
借助专业日期库统一解析逻辑,避免原生API的兼容性问题:
- 安装dayjs:
npm install dayjs --save-dev
- 修改自定义命令:
import dayjs from 'dayjs'; Cypress.Commands.add('compareDates', (expectedDate, actualDate) => { actualDate.then(date => { const dateText = date.text().trim(); // 指定UI日期格式进行解析,转为标准ISO日期字符串 const actualIsoDate = dayjs(dateText, 'DD-MMM-YYYY').format('YYYY-MM-DD'); // 解析数据库日期并格式化 const expectedIsoDate = dayjs(expectedDate).format('YYYY-MM-DD'); cy.log('Actual ISO Date: ' + actualIsoDate) cy.log('Expected ISO Date: ' + expectedIsoDate) expect(actualIsoDate).to.equal(expectedIsoDate); }) })
内容的提问来源于stack exchange,提问作者user9847788
相关产品推荐
相关产品推荐

