Jest测试中Intl.NumberFormat无法识别nanosecond的问题求助
解决Jest中Intl.NumberFormat不识别'nanosecond'的问题
问题背景
我编写了一段用Intl.NumberFormat格式化数字的代码,配置如下:
const formatterOptions: Intl.NumberFormatOptions = { style: 'unit', unit: 'nanosecond', };
这段代码在浏览器环境运行完全正常,也符合Intl.NumberFormat官方文档对nanosecond单位的支持说明,但在Jest执行单元测试时,却抛出了错误:
RangeError: Invalid unit argument for Intl.NumberFormat() 'nanosecond'
我尝试过以下方法,但都没解决问题:
- 安装
full-icu(但Node.js官方说明已内置完整ICU数据,安装后无效) - 升级到Jest 29+和
jest-environment-jsdom29+
可行解决方案
1. 手动Mock Intl.NumberFormat
在测试文件或Jest的全局setup文件中,通过Proxy拦截Intl.NumberFormat的构造,针对nanosecond的情况做自定义处理:
// 可放在jest.setup.js或单个测试文件头部 const originalNumberFormat = Intl.NumberFormat; Intl.NumberFormat = new Proxy(originalNumberFormat, { construct(target, args) { const [_, options] = args; if (options?.style === 'unit' && options?.unit === 'nanosecond') { return { format: (num) => `${num} ns` }; } return new target(...args); } });
这样既不影响其他Intl功能的测试,又能让nanosecond单位的格式化逻辑正常通过测试。
2. 升级测试环境的Node.js版本
nanosecond作为Intl.NumberFormat的单位是较新的ECMA-402特性,部分旧版本Node.js可能未支持。先在终端验证当前Node.js是否支持:
node -e "new Intl.NumberFormat('en-US', {style: 'unit', unit: 'nanosecond'}).format(100)"
如果执行报错,说明当前Node.js版本不支持,建议升级到Node.js 16.x及以上版本。
3. 配置jsdom启用完整Intl支持
在jest.config.js中添加jsdom的环境配置,确保其使用完整的Node.js Intl实现:
module.exports = { testEnvironment: 'jsdom', testEnvironmentOptions: { customExportConditions: ['node', 'node-addons'], }, };
该配置会让jsdom优先使用Node.js内置的完整Intl API,而非自身简化的实现。
内容的提问来源于stack exchange,提问作者chris
相关产品推荐
相关产品推荐

