Jest: test Intl.DateTimeFormat

后端 未结 3 900
星月不相逢
星月不相逢 2021-02-19 12:06

I would like to test a filter function I wrote which return a date formatted using Intl.DateTimeFormat(\'en-GB\', options):

// module \"date.js\"
export default          


        
相关标签:
3条回答
  • 2021-02-19 12:11

    The only solution that I managed to find to this problem was to install full-icu which seemed to provide the right locales to node during the testing process.

    That package is needed because node by default only ships with a limited set of locales, explained here: https://nodejs.org/docs/latest-v9.x/api/intl.html

    With that package installed, the additional step that I had to take was to change my test command to use:

    "test": "NODE_ICU_DATA=node_modules/full-icu jest --config jest.config.js"

    I ran into this problem in a couple of different environments. When running the tests locally on Mac OS and also when running the tests inside a Docker container during CI.

    Interestingly, I don't need to use the export when running the tests via WebStorm's Jest integration. It definitely seems like the behaviour of the Intl library is far from stable in node.

    0 讨论(0)
  • 2021-02-19 12:12

    In package.json add the intl package

     "intl": "*",
    

    In the jest.config.js

    module.exports = {
        moduleNameMapper: {
            Intl: '<rootDir>/node_modules/intl/'
        }
    };
    

    Then in Date.spec.js

     describe(`Date by locale`, () => {
         beforeAll(() => {  global.Intl = require('intl'); });
        // Add your tests here. 
        // Add a temporary console.log to verify the correct output
     }
    
    0 讨论(0)
  • 2021-02-19 12:25

    You can use polyfill, as described here

    import IntlPolyfill from 'intl';
    import 'intl/locale-data/jsonp/ru';
    
    if (global.Intl) {
        Intl.NumberFormat = IntlPolyfill.NumberFormat;
        Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
    } else {
        global.Intl = IntlPolyfill;
    }
    
    0 讨论(0)
提交回复
热议问题