Intl.NumberFormat behaves incorrectly in Jest unit test?
Asked Answered
N

5

15

The Mozilla site says:

var number = 123456.789;

console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' })
.format(number));

// expected output: "123.456,79 €"

But in my Jest unit test, I get as output € 123,456.79 which is not correct for fr-FR locale according to me and Mozilla example.

I've tried to load polyfills and locale data, but it does not seem to resolve the issue

import 'intl';
import 'intl/locale-data/complete';
import 'intl/locale-data/jsonp/fr';
import 'intl/locale-data/jsonp/fr-FR';
import 'intl/dist/Intl.complete';

Any idea what could be wrong?

Nomenclator answered 14/9, 2018 at 10:3 Comment(3)
I have exactly the same problem with EUR!Annihilation
do you found the solution?Annihilation
@AralRoca I posted my own answer here: https://mcmap.net/q/776284/-intl-numberformat-behaves-incorrectly-in-jest-unit-test but didn't try itNomenclator
B
10

A solution that worked for me is:

  1. npm i full-icu
  2. Run your test with NODE_ICU_DATA=node_modules/full-icu jest
Buchner answered 18/8, 2019 at 13:41 Comment(0)
N
6

Answering my own question.

I think this is because we have to provide locales / ICU data to node. Loading the polyfill afterward does not patch the Intl api that is already present in node.

Didn't test further but these links can be helpful:

Jest: test Intl.DateTimeFormat https://github.com/nodejs/node/blob/master/doc/api/intl.md

Nomenclator answered 19/9, 2018 at 16:36 Comment(0)
N
2

For anyone interested, Node >= 13 has full-icu support enabled by default: https://nodejs.medium.com/node-js-12-to-lts-and-node-js-13-is-here-e28d6a4a2bd

Nomenclator answered 2/4, 2021 at 10:18 Comment(0)
S
1

Looks like an inconsistency between node and browser behavior. I think polyfills might not have worked, because your node has support for Intl. And there is a check to avoid overriding the native implementation. Try using IntlPolyfill, it should be available. I also tried node 6.14.4, and got €123,456.79 :D

Sohn answered 14/9, 2018 at 15:36 Comment(2)
Hi. Isn't using IntlPolyfill already what I'm trying to do or another package?Nomenclator
Yeah, no, it is the same package. It's another global that the package exports. It always exports IntlPolyfill, and if Intl is not defined, I will make an alias for Intl.Sohn
E
1

Please check node version first before other trials, because my previous node version was v10.16.0, and I have updated to v12.12.3 which is working for me.

And also, please add this currentDisplay: 'narrowSymbol' in your number format object, something like this:

{Intl.NumberFormat('en-AU', { style: 'currency', currency: 'AUD', currencyDisplay: 'narrowSymbol' }).format(
          (amount)
        )}
Epicalyx answered 26/8, 2021 at 4:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.