0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jestでnext/linkの呼び出しを検証する方法

Posted at

Next.js のアプリケーションでは、ページ遷移に next/link を利用するケースが多くあります。テスト時に実際の遷移を行わず、コンポーネント内部で next/link が呼び出されているかどうかを確認するには、モック化を活用するのが有効です。ここでは、Jest のモック機能を用いて、next/link が正しく呼び出されるかを toHaveBeenCalled で検証する方法を解説します。

next/link のモック化

Jest の jest.mock を使って、next/link をモック化します。以下のコード例では、next/link のデフォルトエクスポートを jest.fn でラップし、実際には <a> タグとしてレンダリングされるようにしています。これにより、リンクコンポーネントがレンダリングされた際の呼び出し状況を簡単に追跡できます。

// テストファイル内でモックを定義する例
jest.mock('next/link', () => {
  return {
    __esModule: true,
    default: jest.fn(({ children, href, ...props }) => (
      <a href={href} {...props}>{children}</a>
    ))
  };
});

サンプルコード

ここでは、next/link を利用したシンプルなコンポーネントと、そのテストコードのサンプルを示します。

コンポーネント例:MyComponent.jsx

import React from 'react';
import Link from 'next/link';

const MyComponent = () => (
  <div>
    <Link href="/about">
      <a>Aboutページへ</a>
    </Link>
  </div>
);

export default MyComponent;

テストコード例:MyComponent.test.jsx

import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';
import Link from 'next/link';

// モック定義(グローバルなモックが未定義の場合のみ)
jest.mock('next/link', () => {
  return {
    __esModule: true,
    default: jest.fn(({ children, href, ...props }) => (
      <a href={href} {...props}>{children}</a>
    ))
  };
});

describe('MyComponent', () => {
  it('next/linkが呼び出されていることを検証', () => {
    render(<MyComponent />);
    // コンポーネントのレンダリング時に next/link のモックが呼ばれているか確認
    expect(Link).toHaveBeenCalled();
  });
});

解説

  • モック化のポイント:
    next/link を jest.fn でラップすることで、コンポーネント内部での呼び出しを追跡可能にしています。実際には <a> タグとしてレンダリングされるため、DOM の構造はシンプルなままです。

  • 呼び出し検証:
    テスト内で render 関数を用いて MyComponent を描画し、その際に next/link のモックが呼び出されることを toHaveBeenCalled で確認します。これにより、リンクコンポーネントが意図した通りに利用されているかどうかをチェックできます。

まとめ

今回の記事では、Next.js の next/link を Jest でモック化し、呼び出し検証を行う方法を紹介しました。モック化を利用することで、コンポーネント間の依存関係を切り離し、シンプルかつ効果的なユニットテストが実現できます。自身のプロジェクトでも、この手法を活用してテストの充実化を図ってみてください。

Happy Testing!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?