LoginSignup
1
1

Next.jsのApp Router対応のnext-export-i18を使った場合にCypressでuseTransrationをモックする

Posted at

Next.js において、exportを使ってサイトを公開する場合の多言語化で next-export-i18n を利用する場合、
next-export-i18n は Next.js のルータの仕組みを使っているため、
CypressのコンポーネントテストではRouterをモックする必要が出てきます。

next-export-i18n の 2.x.x では、基本的にPage Routerのみに対応していたため、
以下のように next/router をモックすることで、テストが可能でしたので共有いたします。


import * as Router from "next/router";

const router = {
  query: {
    id: undefined,
    lang: "ja"
  },
  pathname: "/",
  push: cy.stub()
};
cy.stub(Router, "useRouter").returns(router);

しかしながら、 Next.js の App Router に対応した next-export-i18n の 3.0.0 以降では、
next-export-i18n 内で利用される Next.js のルータが "next/router" ではなく "next/navigation" となり、直接ルータをモックできなくなります。

その場合、useTranslationのみをモックさせる場合、以下のように直接 useTranslation() をモックすることができます。

import * as nextExportI18n from "next-export-i18n";
import translation from "i18n/translations/ja.js"; //next-export-i18nで利用している翻訳のファイル

const useTranslationReturns = {
  t: (key: string) => translation[key] ?? key
};
cy.stub(nextExportI18n, "useTranslation").returns(useTranslationReturns);
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1