Sub topic 15
Testing translated components
This chapter shows how to test React components that use react-i18next. It assumes you know React Testing Library (queries, render, userEvent), have a test runner such as Vitest or Jest, and have the useTranslation, Trans and LanguageSwitcher examples from the earlier chapters. The examples use Vitest with jsdom and flat JSON catalogs at src/locales/en.json and src/locales/de.json.
What to test
Tests for translated UI do not check that a translation reads well. Translators and reviewers do that. The tests check the wiring:
- A component calls
twith the right key and variables. - The right plural form appears for each count.
- Every locale has the keys the code asks for.
- Switching the language updates both the rendered text and the
htmlattributes. - Embedded markup from
Transends up as real elements.
Keep the layers separate. Catalog checks run without React, component tests render under one locale, and a few interaction tests cover switching.
Why not reuse the app's i18n instance
The i18n.ts module from the setup chapter exports a global singleton. If one test calls changeLanguage('de'), every later test in the same file starts in German. The singleton also pulls in language detection or lazy loading, which makes tests depend on the environment.
Create a fresh instance for each render with createInstance(), and give it the catalogs directly. This also lets the test fail on missing keys, which the production configuration usually hides behind a fallback language.
Test setup
Add jest-dom matchers and a jsdom environment to the Vitest configuration:
// vitest.config.ts
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'jsdom',
setupFiles: ['./src/test/setup.ts'],
},
});// src/test/setup.ts
import '@testing-library/jest-dom/vitest';A render helper
The helper builds an isolated instance, wraps the component in I18nextProvider, and records every missing key. It sets fallbackLng: false, so a key missing from German is reported instead of silently showing English.
// src/test/renderWithI18n.tsx
import type { ReactElement } from 'react';
import { render } from '@testing-library/react';
import { createInstance } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import en from '../locales/en.json';
import de from '../locales/de.json';
export async function renderWithI18n(ui: ReactElement, lng = 'en') {
const missing: string[] = [];
const i18n = createInstance();
await i18n.use(initReactI18next).init({
resources: { en: { translation: en }, de: { translation: de } },
lng,
fallbackLng: false,
interpolation: { escapeValue: false },
saveMissing: true,
missingKeyHandler: (lngs, _ns, key) => {
missing.push(`${lngs.join(',')}:${key}`);
},
});
const result = render(<I18nextProvider i18n={i18n}>{ui}</I18nextProvider>);
return { ...result, i18n, missing };
}Two details matter here. init returns a promise, so the helper is async and tests must await it. missingKeyHandler only runs when saveMissing is true, so setting the handler alone does nothing.
Testing text, variables and plurals
Plural forms are the most common source of i18n bugs, and test.each makes them cheap to cover. Include a count of 0 for English, because 0 belongs to the other category there, so the expected text is "0 items".
// src/Cart.test.tsx
import { describe, expect, it } from 'vitest';
import { screen } from '@testing-library/react';
import { Cart } from './Cart';
import { renderWithI18n } from './test/renderWithI18n';
describe('Cart', () => {
it('greets the user by name', async () => {
await renderWithI18n(<Cart name="Ada" count={2} />, 'de');
expect(screen.getByRole('heading', { name: 'Hallo, Ada!' })).toBeInTheDocument();
});
it.each([
['en', 0, '0 items in your cart'],
['en', 1, '1 item in your cart'],
['en', 2, '2 items in your cart'],
['de', 1, '1 Artikel in Ihrem Warenkorb'],
['de', 5, '5 Artikel in Ihrem Warenkorb'],
])('renders %s with count %i', async (lng, count, text) => {
const { missing } = await renderWithI18n(<Cart name="Ada" count={count} />, lng);
expect(screen.getByText(text)).toBeInTheDocument();
expect(missing).toEqual([]);
});
});The missing assertion is the important part. A typo such as t('itmes', { count }) would otherwise render the raw key, and a loose query could still pass.
Prefer roles over translated strings
Queries such as getByText('Hello, Ada!') tie the test to one catalog wording. When a copywriter changes "Hello" to "Welcome", the test breaks even though nothing is wrong.
Use this order of preference:
- Query by role and accessible name where the name is part of what you test, as in the heading above.
- Query by role only (
getByRole('button')) when the text is not the point of the test. - Import the catalog value and build the expected string from it when you want to check wiring but not wording.
import en from '../locales/en.json';
expect(screen.getByRole('button', { name: en.checkout })).toBeInTheDocument();Test exact wording only for strings with logic, such as interpolation and plurals.
Testing Trans and markup
Trans should produce real elements. Check roles and attributes instead of HTML strings. This test uses the terms entry from the catalog: I accept the <link>terms of service</link>, <bold>{{name}}</bold>.
// src/Terms.test.tsx
import { expect, it } from 'vitest';
import { screen } from '@testing-library/react';
import { Terms } from './Terms';
import { renderWithI18n } from './test/renderWithI18n';
it('renders the link and the emphasised name', async () => {
await renderWithI18n(<Terms name="Ada" />, 'en');
const link = screen.getByRole('link', { name: 'terms of service' });
expect(link).toHaveAttribute('href', '/terms');
expect(screen.getByText('Ada').tagName).toBe('STRONG');
});If a translator removes a tag from a translation, such as <link>, this test fails instead of the link quietly disappearing.
Testing locale switching
Render the switcher together with content that depends on the locale, change the selection, and assert on both the text and the document attributes. userEvent is asynchronous, so await each call.
// src/LanguageSwitcher.test.tsx
import { expect, it } from 'vitest';
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Cart } from './Cart';
import { LanguageSwitcher } from './LanguageSwitcher';
import { renderWithI18n } from './test/renderWithI18n';
it('switches text, lang and dir', async () => {
const user = userEvent.setup();
await renderWithI18n(
<>
<LanguageSwitcher />
<Cart name="Ada" count={3} />
</>,
'en',
);
await user.selectOptions(screen.getByRole('combobox'), 'de');
expect(await screen.findByText('3 Artikel in Ihrem Warenkorb')).toBeInTheDocument();
expect(document.documentElement.lang).toBe('de');
expect(document.documentElement.dir).toBe('ltr');
});document.documentElement is shared across tests in a file, and the switcher changes it. Reset it in an afterEach (document.documentElement.lang = ''), or the next test sees the previous test's language.
Catalog checks without React
Missing keys in one language are cheaper to catch by comparing the JSON files than by rendering every screen. This test checks that the locales define the same keys, ignoring plural suffixes, because languages have different plural categories. It also checks that translations keep the same {{placeholders}} as the English source.
// src/locales/catalogs.test.ts
import { describe, expect, it } from 'vitest';
import en from './en.json';
import de from './de.json';
type Catalog = Record<string, string>;
const stripPlural = (key: string) => key.replace(/_(zero|one|two|few|many|other)$/, '');
const baseKeys = (catalog: Catalog) =>
[...new Set(Object.keys(catalog).map(stripPlural))].sort();
const placeholders = (text: string) =>
[...text.matchAll(/\{\{\s*(\w+)\s*\}\}/g)].map((m) => m[1]).sort();
describe('catalogs', () => {
it('de defines the same keys as en', () => {
expect(baseKeys(de as Catalog)).toEqual(baseKeys(en as Catalog));
});
it('de keeps the placeholders of en', () => {
const source = en as Catalog;
const target = de as Catalog;
for (const key of Object.keys(source)) {
if (key in target) {
expect(placeholders(target[key]), key).toEqual(placeholders(source[key]));
}
}
});
});This test does not fully cover plurals. A language that needs few and many forms will pass the key check even if one of those forms is absent. For those languages, check the categories reported by new Intl.PluralRules(locale).resolvedOptions().pluralCategories against the suffixes present in the catalog.
Gotchas
| Problem | Cause | Fix |
|---|---|---|
| Test passes in isolation but fails in the full run | Shared global i18n instance or `document.documentElement` state | Use `createInstance()` per render and reset the `lang` and `dir` attributes |
| Raw keys such as `items` appear in output | Missing key, or `init` not awaited | Await the helper and assert `missing` is empty |
| Currency string does not match | `de-DE` formats `1.234,50 €` with a non-breaking space (`\u00A0`) | Write the expected value with `\u00A0`, or compare with `.replace(/\s/g, ' ')` |
| Intl output differs between machines | Node built without full ICU data, or different ICU versions | Use a Node release with full ICU, and pin the version in CI |
| Date test fails on another day or time zone | Test depends on the current time or local zone | Pass a fixed `Date` and set `timeZone` in `Intl.DateTimeFormat` |
Exercise
A test renders <Cart name="Ada" count={1} /> under de and passes, but the German catalog has items_one and items_other spelled item_one and item_other. What in the render helper makes this test fail, and what must the test also assert?
Show answer
With fallbackLng: false, saveMissing: true and a missingKeyHandler, i18next reports the unresolved items key for de. The helper collects it in the missing array, so the test must assert expect(missing).toEqual([]). Without that assertion, the raw key items would be rendered and the test could still pass if it only checked the greeting.
Exercise
Why does the catalog parity test strip suffixes like _one and _other before comparing keys, and what does it still not verify for a language such as Arabic?
Show answer
Languages have different plural categories, so the same base message can be stored under different suffixes in each catalog, and comparing raw keys would flag valid differences. Stripping the suffix compares the message identity instead. The test does not verify that every category the language needs (zero, one, two, few, many, other) is present. To check that, compare the suffixes in the catalog with Intl.PluralRules(locale).resolvedOptions().pluralCategories.