React项目日期格式化Jest测试报RangeError: Invalid time value问题排查
日期格式化代码问题排查
代码本身的问题
你当前的日期处理代码存在鲁棒性缺失的问题:没有处理Date.parse(createdDate)返回NaN的场景。当createdDate是无效的日期字符串时,Date.parse会返回NaN,此时new Date(NaN)会生成一个标记为Invalid Date的无效日期对象,调用Intl.DateTimeFormat.format方法时就会抛出RangeError: Invalid time value。
测试环境报错的可能原因
- 测试数据无效:你在Jest测试用例中模拟的GraphQL返回数据里,
createdDate的值不符合日期规范——比如是null、空字符串、格式错误的字符串(如"2023-13-01"),导致Date.parse解析失败得到NaN,最终触发报错。 - Jest环境的Intl兼容性问题:部分Jest环境对
Intl.DateTimeFormat的支持不完全,但这种情况概率极低,绝大多数场景下还是测试输入的日期值本身无效导致的。
优化建议
给代码加上前置校验或异常捕获,避免无效日期导致的报错:
// 方案1:前置校验日期有效性 const timestamp = Date.parse(createdDate); const messageDate = isNaN(timestamp) ? new Date() : new Date(timestamp); const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const; const displayDate = new Intl.DateTimeFormat('en-GB', options).format(messageDate); // 方案2:异常捕获处理 let displayDate = 'Invalid Date'; try { const messageDate = new Date(Date.parse(createdDate)); const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const; displayDate = new Intl.DateTimeFormat('en-GB', options).format(messageDate); } catch (err) { // 可根据业务需求设置默认显示值或做其他处理 }
内容的提问来源于stack exchange,提问作者cdmt
相关产品推荐
相关产品推荐

