


E2E-testing localized applications can be challenging, translations keys can make test code harder to read and maintain. This article demonstrates how to test i18next translations in React app using Playwright, with a simplified approach that avoids translation keys. The idea can be used in any project with i18next or similar libraries.
This approach builds upon concepts from my previous article about using Playwright fixtures for authorization in RBAC applications (Testing with Playwright: Making Authorization Less Painful and More Readable).
Here's a practical example of how it looks in a test:
const LOCALES = ["en", "es", "zh"]; describe("Author page", () => { for (let locale of LOCALES) { test(`it has a link to articles. {locale: ${locale}}`, async ({ page, tkey }) => { await page.goto("/authors/123"); const link = await page.getByRole("link").nth(0).textContent(); expect(link).toBe(tkey("Mis articulos", "menu")); }); } });
The key concept here is using the actual phrase instead of an i18n key for translation. Traditional approaches often use translation keys, which can be hard to read. For example: expect(link).toBe(t("menu.current_user_articles_link"));. This contradicts the principle of writing easily readable tests.
Implementation: Swapping Translation Keys with Phrases
The implementation revolves around using phrases that correspond to translation keys in tests. Here's an example of a typical translation file:
{ "en": { "menu": { "current_user_articles_link": "My articles" } }, "es": { "menu": { "current_user_articles_link": "Mis articulos" } }, "zh": { "menu": { "current_user_articles_link": "我的文章" } } }
We'll transform this into a swapped JSON format where phrases map to their corresponding keys (using Spanish as the primary language in this example):
{ "Mis articulos": "menu.current_user_articles_link" }
To achieve this transformation, we'll create a utility function that swaps keys and values in the JSON files. Here's the implementation using TypeScript and Deno:
import { readdir, readFile, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; const CONSTANTS = { DIRECTORY_PATH: 'app/public/locale/es', // Path to locale language files SWAPPED_FILE_PATH: 'e2e/fixtures/i18n/es_swapped.json', // Output path for swapped JSON FILE_ENCODING: 'utf8', } as const; interface TranslationObject { [key: string]: string | TranslationObject; } type SwappedTranslations = Record<string record string>>; function swapKeysAndValues(obj: TranslationObject): Record<string string> { const swappedObject: Record<string string> = {}; function traverseObj(value: unknown, path = ''): void { if (value && typeof value === 'object') { for (const [key, val] of Object.entries(value)) { traverseObj(val, path ? `${path}.${key}` : key); } } else if (typeof value === 'string') { swappedObject[value] = path; } } traverseObj(obj); return swappedObject; } const JSON_EXTENSION_REGEX = /\.json$/; async function buildJsonWithNamespaces(): Promise<void> { try { const files = await readdir(CONSTANTS.DIRECTORY_PATH); const result: SwappedTranslations = {}; for (const file of files) { const filePath = join(CONSTANTS.DIRECTORY_PATH, file); const fileContent = await readFile(filePath, CONSTANTS.FILE_ENCODING); const parsedFileContent = JSON.parse(fileContent) as TranslationObject; const swappedContent = swapKeysAndValues(parsedFileContent); const key = file.replace(JSON_EXTENSION_REGEX, ''); result[key] = swappedContent; } await writeFile( CONSTANTS.SWAPPED_FILE_PATH, JSON.stringify(result, null, 2), CONSTANTS.FILE_ENCODING, ); console.info('✅ Successfully generated swapped translations'); } catch (error) { console.error( '❌ Failed to generate swapped translations:', error instanceof Error ? error.message : error, ); process.exit(1); } } console.info('? Converting locale to swapped JSON...'); buildJsonWithNamespaces(); </void></string></string></string>
Run this script using: deno run --allow-read --allow-write path_to_swap.ts
Setting Up i18n for Playwright
Now let's create a fixture for i18n in Playwright. This implementation is inspired by the playwright-i18next-fixture library, but with custom modifications for better control:
import * as fs from "node:fs"; import path from "node:path"; import Backend from "i18next-http-backend"; import { initReactI18next } from "react-i18next"; import { test as base } from "@playwright/test"; import { createInstance, type i18n, type TFunction } from "i18next"; const CONFIG = { TRANSLATIONS_PATH: "translations_path_to_files/or_api_endpoint", SWAPPED_TRANSLATIONS_PATH: "e2e/fixtures/i18n/es_swapped.json", LOCAL_STORAGE_KEY: "locale", SUPPORTED_LANGUAGES: ["es", "en", "zh"] as const, DEFAULT_LANGUAGE: "es", NAMESPACES: ["shared", "menu"] as const, DEFAULT_NS: "shared", } as const; const data = fs.existsSync(CONFIG.SWAPPED_TRANSLATIONS_PATH) ? JSON.parse(fs.readFileSync(CONFIG.SWAPPED_TRANSLATIONS_PATH, "utf8")) : {}; export function findTranslationByKey( key: string, namespace: string, ): string | undefined { const value = data[namespace][key]; if (value && typeof value === "string") return value; throw new Error( `? Translation not found for the namespace "${namespace}" and key "${key}"`, ); } type SupportedLanguage = (typeof CONFIG.SUPPORTED_LANGUAGES)[number]; type Namespace = (typeof CONFIG.NAMESPACES)[number]; export const i18nOptions = { plugins: [Backend, initReactI18next], options: { lng: CONFIG.DEFAULT_LANGUAGE, load: "languageOnly", ns: CONFIG.NAMESPACES, defaultNS: CONFIG.DEFAULT_NS, supportedLngs: CONFIG.SUPPORTED_LANGUAGES, backend: { allowMultiLoading: true, loadPath: CONFIG.TRANSLATIONS_PATH, }, react: { useSuspense: true, }, }, } as const; let storedI18n: i18n | undefined; async function initI18n({ plugins, options, }: typeof i18nOptions): Promise<i18n> { if (!storedI18n?.isInitialized) { const i18n = plugins.reduce( (i18n, plugin) => i18n.use(plugin), createInstance(), ); await i18n.init(options); storedI18n = i18n; return i18n; } return storedI18n; } export type Tkey = (key: string, namespace?: Namespace) => string; interface I18nFixtures { i18n: i18n; t: TFunction; tkey: Tkey; } /* Fixture for i18n functionality. It initializes the i18next instance and checks the language setting in the storageState created by Playwright. Similar technique was used in my RBAC example. For more details, see my article about authorization testing (https://dev.to/a-dev/testing-with-playwright-how-to-make-authorization-less-painful-and-more-readable-3344) and the official Playwright documentation (https://playwright.dev/docs/api/class-browsercontext#browser-context-storage-state). */ export const i18nFixture = base.extend<i18nfixtures>({ i18n: async ({ storageState }, use) => { const i18nInstance = await initI18n(i18nOptions); if (storageState) { try { const data = JSON.parse( fs.readFileSync(path.resolve(storageState as string), "utf8"), ); const localStorage = data?.origins?.[0]?.localStorage; const language = localStorage?.find( (i) => i.name === CONFIG.LOCAL_STORAGE_KEY, )?.value as SupportedLanguage | undefined; if (!language) { throw new Error( `No language setting found in localStorage (key: ${CONFIG.LOCAL_STORAGE_KEY})`, ); } if (!CONFIG.SUPPORTED_LANGUAGES.includes(language)) { throw new Error( `Unsupported language: ${language}. Supported languages: ${CONFIG.SUPPORTED_LANGUAGES.join(", ")}`, ); } // Change language if different from current if (i18nInstance.language !== language) { await i18nInstance.changeLanguage(language); } } catch (error) { throw new Error(`Failed to process storage state: ${error.message}`); } } await use(i18nInstance); }, tkey: async ({ t }, use) => { await use((str?: string, namespace = "shared"): string => { if (!str) return "⭕ Error: no translation"; const tkey = findTranslationByKey(str, namespace); return t(`${namespace}:${tkey}`); }); }, t: async ({ i18n }, use) => { await use(i18n.t); }, }); </i18nfixtures></i18n>
Finally, we can use the i18nFixture in our Playwright tests to handle translations and language settings. To learn more about working with fixtures, check out the official Playwright documentation. I recommend creating an index.ts file that exports all fixtures, which can then be imported into your test files.
import { mergeTests } from '@playwright/test'; import { i18nFixture } from './fixtures/i18n'; const test = mergeTests({ ...i18nFixture, }); export { test };
Wish you happy testing with Playwright and i18next! ?
If you have any questions or suggestions don't hesitate to comment below.
The above is the detailed content of Testing with Playwright: Use iext Translations in Tests, but not `t(key)`. For more information, please follow other related articles on the PHP Chinese website!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
