我遇到了一个问题,其中 Intl.NumberFormat
以某种不同于 Jest 预期的方式格式化空格字符。使用不产生空格的值对同一函数进行测试,因为分隔符可以正常通过。 Jest 正在考虑第 4 个字符和第 5 个字符之间的空格不同。我在我的应用程序和测试中都为 fr_CA 使用了 intl
polyfill。
这是我的函数,但唯一真正相关的部分是 Intl.NumberFormat
输出。如何协调空格字符的格式以便我的测试通过?
export function formatCurrency( num, locale = 'en_US', showFractionDigits = false) {
const options = {
style: locale === 'fr_CA' ? 'decimal' : 'currency',
currency: locale.length && locale.indexOf('CA') > -1 ? 'CAD' : 'USD'
};
const final = new Intl.NumberFormat(locale.replace('_', '-'), options).format(num);
if (locale === 'fr_CA') {
return `${final} $`;
} else {
return final;
}
}
我的主张:
expect(formatCurrency(24555.55, 'fr_CA', true)).toBe('24 555,55 $');
结果:
Expected value to be:
"24 555,55 $"
Received:
"24 555,55 $"
最佳答案
'11 111.11'.split('').map(x => console.log((x.charCodeAt(0))))
对于普通空格的空格字符产生“32”。
new Intl.NumberFormat('fr-CA').format(11111.11).split('').map(x => console.log((x.charCodeAt(0))))
为空格字符生成“160”,这是一个不间断空格。
要使这些测试通过,您需要在断言中添加不间断空格 UTF-16 (\xa0) 字符代码。
expect(formatCurrency(24555.55, 'fr_CA', true)).toBe('24\xa0555,55 $');
关于javascript - Intl.NumberFormat 空格字符不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54242039/