|
1 |
| -import i18n from "i18next"; |
| 1 | +/** |
| 2 | + * @file Setup internationalization for tests so snapshots and queries reference the correct translations |
| 3 | + */ |
| 4 | +import fs from "fs"; |
| 5 | +import i18n, { InitOptions } from "i18next"; |
| 6 | +import path from "path"; |
2 | 7 | import { initReactI18next } from "react-i18next";
|
3 | 8 |
|
4 | 9 | // @ts-expect-error - Config file has to be .js
|
5 | 10 | import i18nConfig from "../next-i18next.config";
|
6 |
| -import enCommon from "../public/locales/en/common.json"; |
7 |
| -import esCommon from "../public/locales/es/common.json"; |
8 |
| - |
9 |
| -// Setup internationalization for tests so snapshots and queries reference the correct translations |
10 |
| -i18n.use(initReactI18next).init({ |
11 |
| - ...i18nConfig, |
12 |
| - resources: { |
13 |
| - en: { |
14 |
| - common: enCommon, |
15 |
| - }, |
16 |
| - es: { common: esCommon }, |
17 |
| - }, |
18 |
| -}); |
| 11 | + |
| 12 | +const locales = i18nConfig.i18n.locales; |
| 13 | + |
| 14 | +/** |
| 15 | + * Load all of the locales into a single object. A server isn't running for our tests, |
| 16 | + * so we can't load these static assets using HTTP requests like in Storybook. |
| 17 | + * https://www.i18next.com/how-to/add-or-load-translations |
| 18 | + */ |
| 19 | +export const getResources = () => { |
| 20 | + const resources: InitOptions["resources"] = {}; |
| 21 | + |
| 22 | + locales.forEach((locale: string) => { |
| 23 | + resources[locale] = {}; |
| 24 | + |
| 25 | + const namespaces = fs |
| 26 | + .readdirSync(path.resolve(__dirname, `../public/locales/${locale}`)) |
| 27 | + .map((file) => file.replace(/\.json$/, "")); |
| 28 | + |
| 29 | + namespaces.forEach((namespace) => { |
| 30 | + const namespacePath = `../public/locales/${locale}/${namespace}`; |
| 31 | + // eslint-disable-next-line |
| 32 | + resources[locale][namespace] = require(namespacePath); |
| 33 | + }); |
| 34 | + |
| 35 | + return resources; |
| 36 | + }); |
| 37 | + |
| 38 | + return resources; |
| 39 | +}; |
| 40 | + |
| 41 | +i18n |
| 42 | + .use(initReactI18next) |
| 43 | + .init({ |
| 44 | + ...i18nConfig, |
| 45 | + resources: getResources(), |
| 46 | + }) |
| 47 | + .catch((err) => { |
| 48 | + throw err; |
| 49 | + }); |
19 | 50 |
|
20 | 51 | // Export i18n so tests can manually set the language with:
|
21 | 52 | // i18n.changeLanguage('es')
|
|
0 commit comments