javascript - Intl.NumberFormat 空格字符不匹配

标签 javascript unit-testing jestjs

我遇到了一个问题,其中 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/

相关文章:

javascript - ES6 中 "Import"的意义是什么?

javascript - 如何将类添加到上面的第一个 div 中?

javascript - JSON 到数组 react ,jquery

java - 你如何模拟 GroovyTestCase 中的方法?

java - Spring:模拟 beans 的正确方法

typescript - 使用 jsodom 和 jest 测试 react-mapbox-gl

javascript揭示模块模式和jquery

reactjs - 如何在enzyme中调用多个setProps?

javascript - 开 Jest - 引用错误 : imported function is not defined

java - JUnit:具有私有(private)字段的测试生成器