|
| 1 | +import Callout from '@/components/Callout'; |
| 2 | +import Details from '@/components/Details'; |
| 3 | + |
| 4 | +# Testing |
| 5 | + |
| 6 | +Components that use `next-intl` can be used in unit tests: |
| 7 | + |
| 8 | +```tsx |
| 9 | +import {render} from '@testing-library/react'; |
| 10 | +import {NextIntlClientProvider} from 'next-intl'; |
| 11 | +import {expect, it} from 'vitest'; |
| 12 | +import messages from '../../messages/en.json'; |
| 13 | +import UserProfile from './UserProfile'; |
| 14 | + |
| 15 | +it('renders', () => { |
| 16 | + render( |
| 17 | + <NextIntlClientProvider locale="en" messages={messages}> |
| 18 | + <UserProfile /> |
| 19 | + </NextIntlClientProvider> |
| 20 | + ); |
| 21 | +}); |
| 22 | +``` |
| 23 | + |
| 24 | +To avoid having to mock server components, it can be beneficial to define components as [non-async functions](/docs/environments/server-client-components#async-or-non-async), allowing you to flexibly render them in any environment. |
| 25 | + |
| 26 | +## Vitest |
| 27 | + |
| 28 | +`next-intl` is bundled as ESM-only, which requires the usage of [explicit file extensions](https://nodejs.org/api/esm.html#mandatory-file-extensions) internally. However, in order to avoid a [deoptimization in Next.js](https://github.com/vercel/next.js/issues/77200), `next-intl` currently has to import from `next/navigation` instead of `next/navigation.js`. |
| 29 | + |
| 30 | +Vitest correctly assumes a file extension though, therefore for the time being, if you're using [`createNavigation`](/docs/routing/navigation), you need to ask Vitest to process imports within `next-intl`: |
| 31 | + |
| 32 | +```tsx |
| 33 | +import {defineConfig} from 'vitest/config'; |
| 34 | + |
| 35 | +export default defineConfig({ |
| 36 | + test: { |
| 37 | + server: { |
| 38 | + deps: { |
| 39 | + // https://github.com/vercel/next.js/issues/77200 |
| 40 | + inline: ['next-intl'] |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | +}); |
| 45 | +``` |
| 46 | + |
| 47 | +## Jest |
| 48 | + |
| 49 | +Since Jest doesn't have built-in ESM support, you need to instruct Jest to transform imports from `next-intl`: |
| 50 | + |
| 51 | +```tsx |
| 52 | +const nextJest = require('next/jest'); |
| 53 | + |
| 54 | +const createJestConfig = nextJest({dir: './'}); |
| 55 | + |
| 56 | +module.exports = async () => ({ |
| 57 | + ...(await createJestConfig({ |
| 58 | + testEnvironment: 'jsdom', |
| 59 | + rootDir: 'src' |
| 60 | + })()), |
| 61 | + // https://github.com/vercel/next.js/issues/40183 |
| 62 | + transformIgnorePatterns: ['node_modules/(?!next-intl)/'] |
| 63 | +}); |
| 64 | +``` |
0 commit comments