Home Web Front-end JS Tutorial Testing with Playwright: Use iext Translations in Tests, but not `t(&#key&#)`

Testing with Playwright: Use iext Translations in Tests, but not `t(&#key&#)`

Jan 06, 2025 am 07:01 AM

Testing with Playwright: Use iext Translations in Tests, but not `t(

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"));
    });
  }
});
Copy after login

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": "我的文章"
    }
  }
}
Copy after login

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"
}
Copy after login

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, 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();
Copy after login

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);
  },
});
Copy after login

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 };
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles