Intl.NumberFormat空格字符不匹配 [英] Intl.NumberFormat space character does not match

查看:61
本文介绍了Intl.NumberFormat空格字符不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个问题,其中 Intl.NumberFormat 正在以某种不同于Jest期望的方式格式化空格字符.针对相同的函数进行测试,其值不会因分隔符通过而产生空格.笑话正在考虑4个字符和5个字符之间的空格是不同的.我在我的应用程序和测试中都将 intl polyfill用于fr_CA.

I'm running into an issue where Intl.NumberFormat is formatting the space character in some way that is different from what Jest is expecting. Tests against the same function with values that do not yield spaces as separators pass fine. Jest is considering the space between the 4 and the 5 characters to be different. I am using the intl polyfill for fr_CA both in my app and in my test.

这是我的函数,但唯一真正相关的部分是 Intl.NumberFormat 输出.如何协调空格字符的格式,以便测试通过?

Here is my function, but the only really relevant part is the Intl.NumberFormat output. How can I reconcile the formatting for the space character so that my test passes?

  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".

Yields "32" for the space character which is a normal space.

new Intl.NumberFormat('fr-CA').format(11111.11).split('').map(x => console.log((x.charCodeAt(0))))

空格字符为"160",这是一个不间断空格.

Yields "160" for the space character, which is a non-breaking space.

要使这些测试通过,您需要在断言中添加不间断空格UTF-16(\ xa0)字符代码.

To make these tests pass, you need to add the non-breaking space UTF-16 (\xa0) character code into the assertion.

expect(formatCurrency(24555.55, 'fr_CA', true)).toBe('24\xa0555,55 $');

这篇关于Intl.NumberFormat空格字符不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆