I'm trying to create a unit test for my nextjs-component using next-intl.
My component:
import Head from "next/head";
import { useTranslations } from "next-intl";
export default function Home() {
const t = useTranslations("HomePage");
return (
<div>
<Head>
<title>My title goes here</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<h1>{t("welcome")}</h1>
</div>
);
}
// Get localized messages
export function getStaticProps({ locale }) {
return {
props: {
messages: require(`locales/${locale}.json`),
},
};
}
How can one create a unit test in lines of:
import Home from '../pages/index'
describe('Home', () => {
it('renders a heading', () => {
render(<Home />)
const heading = screen.getByRole('heading', {level: 1})
expect(heading).toBeInTheDocument()
})
})
Have tried to mock next-intl without any luck. Also tried to wrap Home in a <NextIntlProvider messages={localization}> where localization is a json containing localized strings, but it still states locale is null. If anyone could help me write a simple unit test or an example of a unit test for a component using next-intl, it would be much appreciated.
Links to docs:
i18n Next: https://nextjs.org/docs/advanced-features/i18n-routing
next-intl: https://formatjs.io/docs/getting-started/installation/
UPDATE: now working :)
I managed to run my test with the following setup:
import React from 'react'
import { render, screen } from '@testing-library/react'
import { NextIntlProvider } from "next-intl";
import Home from '../pages/index'
describe('Home Component', () => {
const useRouter = jest.spyOn(require('next/router'), 'useRouter')
const locale = 'no-NB';
const messages = require(`../locales/${locale}.json`);
useRouter.mockImplementationOnce(() => ({
query: { locale: locale },
}))
it('renders a heading', () => {
render(
<NextIntlProvider messages={messages} locale={locale}>
<Home />
</NextIntlProvider>
)
const heading = screen.getByRole('heading', {level: 1})
expect(heading).toBeInTheDocument()
})
})