3

I'm trying to properly mock my i18n file with typescript and jest but I keep getting this error when I run the test:

  TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
    __tests__/__mock__/react-i18next.ts:1:1 - error TS1208: All files must be modules when the '--isolatedModules' flag is provided.

    1 jest.mock('i18next', () => ({

react-i18next.ts:

jest.mock('i18next', () => ({
  use: () => {
    return {
      init: () => { }
    };
  },
  t: k => k
}));

My jest.config:

module.exports = {
  verbose: true,
  roots: ["<rootDir>"],
  testRegex: "/__tests__/.*\\.(test|spec)\\.tsx?",
  transform: {
    "^.+\\.tsx?$": "ts-jest",
  },
  moduleNameMapper: {
    "react-i18next": "<rootDir>/__tests__/__mock__/react-i18next.ts"
  },
};

i18n.ts

import i18n from "i18next";
import {initReactI18next} from "react-i18next";
import english from "./locales/en/common.json";
import french from "./locales/fr/common.json";

i18n.use(initReactI18next).init({
  lng: 'en',
  resources: {
    fr: {
      translation: french,
    },
    en: {
      translation: english,
    },
  },
  interpolation: {
    escapeValue: false,
  },
  fallbackLng: ["en"]
});

export default i18n;
skyboyer
  • 22,209
  • 7
  • 57
  • 64
lost9123193
  • 10,460
  • 26
  • 73
  • 113
  • This answer might help: https://stackoverflow.com/questions/56577201/why-is-isolatedmodules-error-fixed-by-any-import/56577324 – user2740650 Jan 19 '20 at 04:14
  • @user2740650 thanks. Sorry I'm not sure what changes I would have to make on this file? – lost9123193 Jan 19 '20 at 04:18
  • I just thought that exporting something from `react-i18next.ts:` might fix it. Eg `export {}` at the end of that file. Just something to try based on that other answer. – user2740650 Jan 19 '20 at 16:56

1 Answers1

0

When you put a file inside __mocks__ you don't need to map it using

moduleNameMapper: {
  "react-i18next": "<rootDir>/__tests__/__mock__/react-i18next.ts"
},

In order to achieve your mock implementation, you can configure i18next to use a special language called cimode that will do exactly what you are trying to to with your mock.

Instead of mocking he lib, try to make a separate configuration of i18next with using that cimode language.

felixmosh
  • 32,615
  • 9
  • 69
  • 88