michaelwittig / node-i18n-iso-countries

i18n for ISO 3166-1 country codes
MIT License
807 stars 261 forks source link

Jest: `TypeError: Cannot read property 'registerLocale' of undefined` #279

Open asode opened 2 years ago

asode commented 2 years ago

Hi, I was wondering what am I doing wrong here as I'm trying to test my component with jest. In browser it works fine. Should I somehow exclude the language imports from jest run as it doesn't run in a browser (just speculating)?

node 14.17.3
npm 8.5.0
i18n-iso-countries@7.3.0
jest@27.5.1
@testing-library/dom@8.11.3
@testing-library/jest-dom@5.16.2
@testing-library/svelte@3.0.3
@testing-library/user-event@13.5.0
import countries from "i18n-iso-countries"

```js // Register.svelte import countries from "i18n-iso-countries"; import countriesEnglish from "i18n-iso-countries/langs/en.json"; countries.registerLocale(countriesEnglish); ``` Jest outputs the following error: ```js TypeError: Cannot read property 'registerLocale' of undefined 13 | import countriesEnglish from "i18n-iso-countries/langs/en.json"; > 14 | countries.registerLocale(countriesEnglish); | ^ at instance (src/components/register/Register.svelte:14:13) at init (node_modules/svelte/internal/index.js:1865:11) at new Register (src/components/register/Register.svelte:604:3) at render (node_modules/@testing-library/svelte/dist/pure.js:81:21) at Object. (src/components/register/Register.test.ts:145:11) ```


Also tried import * (inspired by #125), but it only caused a different error:

import * as countries from "i18n-iso-countries"

```js // Register.svelte import * as countries from "i18n-iso-countries"; import countriesEnglish from "i18n-iso-countries/langs/en.json"; countries.registerLocale(countriesEnglish); ``` Jest outputs the following error: ```js TypeError: Cannot read property 'locale' of undefined 13 | import countriesEnglish from "i18n-iso-countries/langs/en.json"; > 14 | countries.registerLocale(countriesEnglish); | ^ at Object..exports.registerLocale (node_modules/i18n-iso-countries/index.js:99:19) at instance (src/components/register/Register.svelte:14:13) at init (node_modules/svelte/internal/index.js:1865:11) at new Register (src/components/register/Register.svelte:607:3) at render (node_modules/@testing-library/svelte/dist/pure.js:81:21) at Object. (src/components/register/Register.test.ts:145:11) ```

asode commented 2 years ago

Got around the issue by mocking the functions:

jest.mock("i18n-iso-countries", () => ({
  default: jest.fn(),
  registerLocale: jest.fn(),
  getNames: jest.fn().mockResolvedValue({ EN: "English" }),
}));

But is this really required? Shouldn't the library work with jest even without mocking?

Gurochka commented 2 years ago

It seems that jest can't find localization files to insert them to registerLocale. Another solution is to add a root path to the jest.config.js file: roots: ["<rootDir>/src", "<rootDir>/node_modules/i18n-iso-countries"]. That worked for me.