Mocha断言日期字符串匹配失败,求JS中其他日期对比方法
Mocha中JavaScript日期字符串断言的替代方法
你遇到的AssertionError核心原因是contains的字面量匹配逻辑:请求日期是带三位毫秒的2023-02-21T20:31:37.690Z,响应日期是两位毫秒的2023-02-21T20:31:37.69Z,前者并不包含后者,所以断言失败。以下是几种更靠谱的日期字符串对比方法:
1. 统一格式后做全等断言
将两个日期字符串转换成统一精度的标准格式,再用to.equal做全等匹配:
// 封装格式化函数,输出带三位毫秒的ISO标准格式 const normalizeDate = (dateStr) => new Date(dateStr).toISOString(); expect(normalizeDate(request.startDate)).to.equal(normalizeDate(response.body.startDate));
2. 转换为时间戳对比
将日期字符串转为Date对象后获取时间戳(数值类型),直接对比数值是否相等:
const requestTimestamp = new Date(request.startDate).getTime(); const responseTimestamp = new Date(response.body.startDate).getTime(); expect(requestTimestamp).to.equal(responseTimestamp);
3. 用正则忽略毫秒精度差异
如果业务允许忽略毫秒部分的精度差异,可以用正则提取到秒级的时间片段再对比:
// 提取到秒级的日期片段 const getSecondLevelDate = (dateStr) => dateStr.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)[0]; expect(getSecondLevelDate(request.startDate)).to.equal(getSecondLevelDate(response.body.startDate));
4. 允许微小时间误差的断言
如果接口响应的日期可能存在几毫秒的误差,可以用Chai的closeTo方法设置允许的误差范围:
const requestTs = new Date(request.startDate).getTime(); const responseTs = new Date(response.body.startDate).getTime(); // 允许前后10毫秒的误差 expect(requestTs).to.be.closeTo(responseTs, 10);
内容的提问来源于stack exchange,提问作者Analyst
相关产品推荐
相关产品推荐

