Sub topic 15
Testing translated components
This chapter assumes you can write React component tests with Vitest (or Jest) and React Testing Library, and that you have the react-i18next setup from the earlier chapters. Translated components are easy to test badly. The usual mistakes are sharing one global i18n instance between tests and asserting on text that changes whenever a translator edits a message.
Give each test its own i18n instance
If tests call i18n.changeLanguage on the app's shared instance, one test can leave the language set for the next. Instead, create a fresh instance with createInstance() and pass it down through I18nextProvider. A small helper keeps this out of the individual tests.
// test-utils.tsx
import type { ReactElement } from 'react';
import { render } from '@testing-library/react';
import i18next from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
// In a real project, import your JSON catalogs here instead.
export const resources = {
en: {
translation: {
greeting: 'Hello, {{name}}!',
items_one: '{{count}} item in your cart',
items_other: '{{count}} items in your cart',
},
},
de: {
translation: {
greeting: 'Hallo, {{name}}!',
items_one: '{{count}} Artikel in Ihrem Warenkorb',
items_other: '{{count}} Artikel in Ihrem Warenkorb',
},
},
};
export async function renderWithI18n(ui: ReactElement, lng = 'en') {
const instance = i18next.createInstance();
await instance.use(initReactI18next).init({
resources,
lng,
fallbackLng: 'en',
interpolation: { escapeValue: false },
});
return render(<I18nextProvider i18n={instance}>{ui}</I18nextProvider>);
}The helper is async because init returns a promise. Awaiting it means the catalogs are ready before the first render.
Test the behaviour, in a chosen locale
Render the Cart component from the earlier chapter under each locale you care about. Cover at least one plural boundary, since that is where translation bugs hide.
// Cart.test.tsx
import { screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
import { Cart } from './Cart';
import { renderWithI18n } from './test-utils';
describe('Cart', () => {
it('fills in the name in English', async () => {
await renderWithI18n(<Cart name="Ada" count={2} />);
expect(screen.getByRole('heading', { name: 'Hello, Ada!' })).toBeDefined();
});
it('uses the singular form for one item', async () => {
await renderWithI18n(<Cart name="Ada" count={1} />);
expect(screen.getByText('1 item in your cart')).toBeDefined();
});
it('renders German when asked', async () => {
await renderWithI18n(<Cart name="Ada" count={3} />, 'de');
expect(screen.getByText('3 Artikel in Ihrem Warenkorb')).toBeDefined();
});
});getByText and getByRole throw when nothing matches, so each assertion fails loudly without extra matchers.
Check the catalogs themselves
Component tests only see the keys they render. A second test can compare the catalogs so a key added in English cannot silently miss German.
// catalogs.test.ts
import { expect, it } from 'vitest';
import { resources } from './test-utils';
const keysOf = (lng: keyof typeof resources) =>
Object.keys(resources[lng].translation).sort();
it('German has every English key', () => {
expect(keysOf('de')).toEqual(keysOf('en'));
});This works here because English and German both use _one and _other. Languages with more plural categories, such as Polish or Arabic, need extra suffixes. For those, compare keys after stripping the plural suffix.
Common errors
- Raw keys in the output. If you see
greetinginstead ofHello, Ada!, the test rendered without a provider, orinithad not finished. Await the helper. - Leaking language between tests. This happens when you use the global instance. Use
createInstance(). - Brittle text assertions. Assert on exact strings only where the test controls the catalog, as here. For the real catalogs, prefer roles and labels, or assert on the values interpolated into the message.
- No cleanup between tests. Without
globals: truein the Vitest config, React Testing Library does not clean up automatically. Set it, or callcleanup()inafterEach.
Exercise
Why does the test helper call i18next.createInstance() instead of importing the app's shared i18n object?
Show answer
A fresh instance gives every test its own language and catalogs. With the shared instance, a changeLanguage('de') in one test would still be active in the next, so results would depend on test order.