Search code examples
javascriptnumber-formatting

When running tests with Jest, how do I get Intl.NumberFormat to recognize nanosecond?


I have some JavaScript code that uses Intl.NumberFormat to format numbers. Specifically, I am using it with these options:

  const formatterOptions: Intl.NumberFormatOptions = {
    style: 'unit',
    unit: 'nanosecond',
  };

When I run this code in the browser, the formatting works. This make sense, because the Intl.NumberFormat documentation indicates that it can support nanoseconds.

When I run a unit test with Jest, I get this error:

RangeError: Invalid unit argument for Intl.NumberFormat() 'nanosecond'

--

It seems like the code running in the Jest environment is not aware of 'nanosecond'.

I found a previous question that suggested that installing full-icu might fix the Jest unit test.

However, the full-icu project says this should no longer be necessary; node should have the full-icu data already.

I tried installing full-icu and still got the error.

I updated to the latest versions of jest (29+) and jest-environment-jsdom (29+) in case that would help. I still got the error.


Solution

  • Answering my own question:

    Debugged with a co-worker, and we found that the culprit was the version of node.

    Our project is using node 18.4.2. At this version, the tests do not pass. At node 18.17.1 (highest version of 18), the tests do not pass. At node 19.8.1 (highest version of 19), the tests do not pass. At node 20.0.0, the tests do pass!

    We assume that node 20 includes the nanosecond data that is used by Intl.NumberFormat. We assume that this is the same data that is already shipped in the browser, and this is why the code works in the browser.