Skip to content

Guides

Testing

A test does not need the plugin, the virtual module or your catalogs on disk. Build an instance with the messages that test cares about and hand it to the provider. That is how the adapters themselves are tested.

An instance is all you need

createVerbaly takes the messages inline, so a test names the two or three it asserts on and nothing else. No mocking, because there is nothing to mock.

hello.test.tsx
import { createVerbaly } from 'verbaly';
import { VerbalyProvider } from '@verbaly/react';

const verbaly = createVerbaly({
  locale: 'es',
  messages: { es: { hello: 'Hola {name}' } },
});

render(
  <VerbalyProvider instance={verbaly}><Hello /></VerbalyProvider>
);
expect(screen.getByText('Hola Aron')).toBeVisible();

Assert on the text, not the key

Give the instance your source language and your assertions read like the screen does. A test that matches a key is a test that passes while the interface is empty, because a key that resolves to nothing renders as itself.

Changing language in a test

setLocale is asynchronous because a real catalog can be loaded on demand. Await it, then assert. With messages passed inline there is nothing to fetch, so it settles immediately.

switch.test.ts
await verbaly.setLocale('en');
expect(verbaly.t('hello', { name: 'Aron' })).toBe('Hello Aron');

Testing against your real catalogs

Import the JSON and pass it in. It is the same shape either way, flat or nested, because the runtime flattens what it is given. Useful for a snapshot of one screen in every language, and unnecessary for everything else.

screen.test.ts
import es from '../locales/es.json';
const verbaly = createVerbaly({ locale: 'es', messages: { es } });

If a test imports the virtual module

Code that imports from virtual:verbaly needs the plugin present when that file is loaded. In Vitest that means adding the same plugin your app uses to the test config. The simpler path is to keep virtual:verbaly out of the units you test and pass the instance in, which is what the adapters do.

to moveEnterto open
Copied to clipboard