You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 12:25:23