# Testing

Source: https://verbaly.dev/docs/guide/testing

A test does not need the plugin, the project 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.

```tsx title="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` on an instance does not wait. It swaps the language and asks for the catalog behind you, so with a real lazy catalog an assertion on the next line reads the old text. Await `loadLocale` first and then switch. With messages passed inline there is nothing to fetch, so both lines are instant. The `setLocale` of `verbaly/app` does wait: it returns a promise.

```ts title="switch.test.ts"
await verbaly.loadLocale('en');
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.

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

> **You are already testing the translations**
>
> `npx verbaly check` in CI is what verifies every message exists in every language and that each translation can render what its source renders. Your unit tests do not have to repeat that, and a test per language is usually a test of Verbaly rather than of your code.

## If a test imports the project module

Code that imports from `verbaly/app` needs the plugin present when that file is loaded. In Vitest that means adding the same plugin your app uses to the test config, and then a component under test needs no wrapper: with no provider above it, `useT()` reads the instance the plugin creates, as in the browser. The simpler path is still to keep `verbaly/app` out of the units you test and pass the instance in, which is what the adapters do.
