使用 nextjs 和 next-intl 进行组件的 Jest 单元测试

问题描述 投票:0回答:1

我正在尝试使用 next-intl 为我的 nextjs 组件创建一个单元测试。

我的组件:

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`),
    },
  };
}

如何在以下行中创建单元测试:

 import Home from '../pages/index'
 
 describe('Home', () => {
   it('renders a heading', () => {
     render(<Home />)
 
     const heading = screen.getByRole('heading', {level: 1})
 
     expect(heading).toBeInTheDocument()
   })
 })

曾尝试嘲笑 next-intl 但没有任何运气。还尝试将 Home 包装在

<NextIntlProvider messages={localization}>
中,其中本地化是包含本地化字符串的 json,但它仍然声明 locale 为 null。如果有人可以帮助我使用
next-intl
编写一个简单的单元测试或组件的单元测试示例,我将不胜感激。

文档链接:
i18n 下一个:https://nextjs.org/docs/advanced-features/i18n-routing
下一个国际:https://formatjs.io/docs/getting-started/installation/


更新:现在工作:)

我设法使用以下设置运行测试:

 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()
   })
 })
reactjs unit-testing jestjs next.js internationalization
1个回答
-1
投票

你拯救了我的一周@Tvedt 谢谢!!!

© www.soinside.com 2019 - 2024. All rights reserved.