Are there any best practices of how to use i18n inside play-functions? #34845
Replies: 1 comment
-
|
The core tension with i18n in play-functions is that you're deciding what the test actually asserts: the translated string, or the UI behavior. Recommended approach: test by role/testid, not translated text // story
export const MyStory: Story = {
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// find by role — language-agnostic
await userEvent.click(canvas.getByRole('button', { name: /submit/i }));
await expect(canvas.getByRole('alert')).toBeInTheDocument();
},
};This is the most resilient pattern. Translations change; behavior doesn't. When you must assert on translated text: use the i18n instance directly // .storybook/preview.ts
import i18n from '../src/i18n'; // your app's i18n instance
export const decorators = [
(Story) => (
<I18nextProvider i18n={i18n}>
<Story />
</I18nextProvider>
),
];Then in play: play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// i18n is initialized in the decorator — use the same keys
await expect(
canvas.getByText(i18n.t('submit_button_label'))
).toBeInTheDocument();
},This keeps assertions in sync with translations automatically — if the translation key's value changes, the test still passes. When you want isolation: mock the translation function // in your story file or a decorator
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));Now your play-function can assert on the raw key string ( Which to choose:
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Summary
We have i18n app. We want to write some tests using play-functions. Are there any best practices of how to do it better? Should we use i18n.t() inside play-functions? Or there are any other approaches?
Additional information
No response
Create a reproduction
No response
Beta Was this translation helpful? Give feedback.
All reactions