【问题标题】:Intl.NumberFormat space character does not matchIntl.NumberFormat 空格字符不匹配
【发布时间】:2019-06-12 00:20:07
【问题描述】:

我遇到了一个问题,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 $"

【问题讨论】:

  • 我看不出您的预期和收到的差异。你那里有错字吗?
  • 没有错字。这就是这个问题的全部意义所在。

标签: javascript


【解决方案1】:

NumberFormat 使用小的不间断空格 (\u202f) 作为千位分隔符和普通不间断空格 (\xa0)

  expect(new Intl.NumberFormat("fr-FR", {
    style: "currency",
    currency: "EUR",
  }).format(126126)).toBe("126\u202f126,00\xa0€")

【讨论】:

  • 非常感谢分享\u202f 角色!
  • expect(actualResult.replace(/\xa0/g, ' ').replace(/\u202f/g, ' ')).toEqual(expectedResult)
【解决方案2】:
'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 $');

【讨论】:

  • 哇,我花了太多时间来解决这个问题。很高兴我迟到了。
  • 这是什么原因?有没有办法告诉Intl 使用普通的\x20 空格字符?
  • @andersnylund 这是期望/正确的行为。美元和美分永远不应该放在两条不同的线上。这只是您在进行测试之前不会考虑的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多