我遇到了一个问题,Intl.NumberFormat即以与 Jest 期望的方式不同的方式格式化空格字符。使用不产生空格的值对同一函数进行测试,因为分隔符通过正常。Jest 正在考虑 4 和 5 字符之间的空格不同。我intl在我的应用程序和我的测试中都使用了fr_CA 的 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我的主张:
expect(formatCurrency(24555.55, 'fr_CA', true)).toBe('24 555,55 $');
Run Code Online (Sandbox Code Playgroud)
结果:
Expected value to be:
"24 555,55 $"
Received:
"24 555,55 $"
Run Code Online (Sandbox Code Playgroud)
jma*_*svt 20
'11 111.11'.split('').map(x => console.log((x.charCodeAt(0))))
Run Code Online (Sandbox Code Playgroud)
为正常空格的空格字符产生“32”。
new Intl.NumberFormat('fr-CA').format(11111.11).split('').map(x => console.log((x.charCodeAt(0))))
Run Code Online (Sandbox Code Playgroud)
空格字符产生“160”,这是一个不间断的空格。
要使这些测试通过,您需要将不间断空格 UTF-16 (\xa0) 字符代码添加到断言中。
expect(formatCurrency(24555.55, 'fr_CA', true)).toBe('24\xa0555,55 $');
Run Code Online (Sandbox Code Playgroud)
Gui*_*ent 11
NumberFormat 使用小的不间断空格 ( \u202f) 作为千位分隔符,并在货币 ( \xa0) 之前使用正常的不间断空格
expect(new Intl.NumberFormat("fr-FR", {
style: "currency",
currency: "EUR",
}).format(126126)).toBe("126\u202f126,00\xa0€")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2516 次 |
| 最近记录: |