Testing translations

Should your page say “Bienvenido” in Spanish and “Welcome” in English? Check it in Node without starting Astro, opening a browser or mounting components. Use the same message files your project reads.

Prepare the messages

Add these messages to your JSON files. You choose the group name demo and the key title inside it. Then choose the example for your adapter or for Astro itself.

src/i18n/messages/en.json
{
  "demo": {
    "title": "Welcome"
  }
}
src/i18n/messages/es.json
{
  "demo": {
    "title": "Bienvenido"
  }
}

React, Svelte, Preact, Vue and SolidJS

Choose your adapter and save the example as tests/translations.test.mjs. The test passes both catalogs to createGetTranslations and sets English as the default. translate("es", "demo") selects the demo group in the Spanish catalog. tDemo("title") reads its title. The second assertion checks what happens when you omit the locale.

import { test } from "node:test";
import assert from "node:assert/strict";
import { createGetTranslations } from "astro-intl/react";
import en from "../src/i18n/messages/en.json" with { type: "json" };
import es from "../src/i18n/messages/es.json" with { type: "json" };

test("reads the Spanish title and defaults to English", () => {
  const translate = createGetTranslations({ en, es }, "en");
  const tDemo = translate("es", "demo");
  assert.equal(tDemo("title"), "Bienvenido");

  const tDefault = translate(undefined, "demo");
  assert.equal(tDefault("title"), "Welcome");
});

Astro without a UI framework

In an .astro page, getTranslations reads the locale from context. In a test, runWithLocale takes the locale from a URL and runs your function with the catalog you supply. The URL provides the path without making a network request.

tests/astro.test.mjs
import { test } from "node:test";
import assert from "node:assert/strict";
import { getTranslations, runWithLocale } from "astro-intl";
import en from "../src/i18n/messages/en.json" with { type: "json" };
import es from "../src/i18n/messages/es.json" with { type: "json" };

const catalogs = { en, es };

test("reads the title in the page’s language", async () => {
  for (const [lang, expected] of [["es", "Bienvenido"], ["en", "Welcome"]]) {
    const title = await runWithLocale(
      new URL("/" + lang + "/", "https://example.test"),
      () => getTranslations("demo")("title"),
      (locale) => ({ locale, messages: catalogs[locale] })
    );
    assert.equal(title, expected);
  }
});

Run the test

Save your chosen example in your Astro project’s tests directory. From the project root, run the command with Node 22.23.4 or later. If the text changes, the test reports the expected and actual values.

Terminal
node --test