テスト
文言とgetLocale()が読むロケールは、テストの実行環境で決まります。Nodeではlocales.runで、ブラウザではURLでロケールを選びます。
このページの内容
Nodeのテスト
src/messages/nav.test.tsimport { expect, it } from 'vitest';
import { locales } from '../i18n';
import { home } from './nav';
it('renders in the default locale', () => {
expect(home()).toBe('ホーム');
});
it('renders in the locale run names', () => {
expect(locales.run('en', () => home())).toBe('Home');
});
it('keeps the locale across awaits', async () => {
const text = await locales.run('en', async () => {
await Promise.resolve();
return home();
});
expect(text).toBe('Home');
});ロケールを指定しなければ、文言は既定のロケールの文を返します。別のロケールで確かめるときは、locales.runの中で呼びます。
async関数を渡しても、awaitをまたいでロケールは保たれます。同時に動くrunどうしのロケールが互いに影響することもありません。
paramsSchemaのテスト
src/i18n.test.tsimport { expect, it } from 'vitest';
import { locales } from './i18n';
it('accepts only the listed locales', () => {
const { validate } = locales.paramsSchema['~standard'];
expect(
locales.run('ja', () => validate({ locale: 'en' })),
).toStrictEqual({ value: { locale: 'en' } });
expect(validate({ locale: 'fr' })).toMatchObject({
issues: [{ path: ['locale'] }],
});
});paramsSchemaがロケールを受け付けると、呼び出し元の非同期コンテキストの残り全体に、そのロケールが設定されます。テストから直接呼ぶと、後のテストにもロケールが残ります。
ロケールを受け付ける検証はrunの中で呼びます。runを抜けるとロケールは元に戻り、後のテストには残りません。
一覧に無いロケールは受け付けず、ロケールも設定されません。そのためrunで囲まなくてかまいません。
ブラウザのテスト
src/messages/nav.browser.test.tsimport { afterEach, expect, it } from 'vitest';
import { locales } from '../i18n';
import { home } from './nav';
const initial = location.pathname;
afterEach(() => {
history.replaceState(null, '', initial);
});
it('renders in the locale the URL names', () => {
history.replaceState(null, '', '/en/cart');
expect(locales.getLocale()).toBe('en');
expect(home()).toBe('Home');
});Vitestのブラウザモードのような本物のブラウザでは、location.pathnameの先頭の区間がロケールになります。history.replaceStateでパスを書き換え、afterEachで元に戻します。
ブラウザでrunを呼ぶと、locales.run: in the browser the URL is the locale — navigate insteadというエラーになります。jsdomやhappy-domのようにdocumentを定義する環境もブラウザとして扱うので、同じようにURLでロケールを決めます。
テストの中のdefineLocales
vitest.setup.tsimport { defineLocales } from '@k8ordo/i18n';
import { beforeEach } from 'vitest';
import { locales } from './src/i18n';
beforeEach(() => {
defineLocales(locales.definitions, { default: locales.default });
});テストの中でdefineLocalesを呼ぶと、文言が読む集合は最後に定義したものに置き換わります。
テストではアプリのlocalesをimportして使います。別の集合を定義するテストがあるなら、セットアップファイルのbeforeEachでアプリの集合を定義し直します。
型のテスト
src/messages/cart.test.tsimport { message } from '@k8ordo/i18n';
import { expectTypeOf, it } from 'vitest';
import { added } from './cart';
it('types the arguments of a message', () => {
expectTypeOf(added).parameters.toEqualTypeOf<
[name: string]
>();
});
it('refuses a message without every locale', () => {
// @ts-expect-error
message({ ja: '保存' });
});文言の引数の型と、ロケールが欠けたときの型エラーは、型のテストで確かめられます。
@ts-expect-errorを付けた宣言は、ロケールが欠けて型エラーになる限り通ります。ロケールの型がRegisterに登録されずに型エラーが出なくなると、使われない@ts-expect-errorが残り、型チェックが失敗します。