コンテンツにスキップ

Next.js で Cypress をセットアップする方法

Cypress は、**エンドツーエンド (E2E)** および **コンポーネント テスト** に使用されるテストランナーです。このページでは、Next.js で Cypress をセットアップし、最初のテストを作成する方法を説明します。

警告

  • Cypress バージョン 13.6.3 未満では、moduleResolution:"bundler" を使用した TypeScript バージョン 5 はサポートされていません。しかし、この問題は Cypress バージョン 13.6.3 以降で解決されています。cypress v13.6.3

手動セットアップ

Cypress を手動でセットアップするには、cypress を開発依存関係としてインストールします。

ターミナル
npm install -D cypress
# or
yarn add -D cypress
# or
pnpm install -D cypress

Cypress の open コマンドを package.json の scripts フィールドに追加します。

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint",
    "cypress:open": "cypress open"
  }
}

初めて Cypress を実行して、Cypress テストスイートを開きます。

ターミナル
npm run cypress:open

E2E テスト および/またはコンポーネント テスト を構成できます。これらのオプションのいずれかを選択すると、cypress.config.js ファイルと cypress フォルダがプロジェクトに自動的に作成されます。

初めての Cypress E2E テストを作成する

cypress.config ファイルが次の構成になっていることを確認してください。

cypress.config.ts
import { defineConfig } from 'cypress'
 
export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})

次に、2 つの新しい Next.js ファイルを作成します。

pages/index.js
import Link from 'next/link'
 
export default function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
pages/about.js
import Link from 'next/link'
 
export default function About() {
  return (
    <div>
      <h1>About</h1>
      <Link href="/">Home</Link>
    </div>
  )
}

ナビゲーションが正しく機能しているかを確認するテストを追加します。

cypress/e2e/app.cy.js
describe('Navigation', () => {
  it('should navigate to the about page', () => {
    // Start from the index page
    cy.visit('https://:3000/')
 
    // Find a link with an href attribute containing "about" and click it
    cy.get('a[href*="about"]').click()
 
    // The new url should include "/about"
    cy.url().should('include', '/about')
 
    // The new page should contain an h1 with "About"
    cy.get('h1').contains('About')
  })
})

E2E テストを実行する

Cypress はユーザーがアプリケーションを操作する様子をシミュレートします。これには Next.js サーバーの実行が必要です。アプリケーションの動作に最も近い状態にするために、本番コードに対してテストを実行することをお勧めします。

npm run build && npm run start を実行して Next.js アプリケーションをビルドし、別のターミナルウィンドウで npm run cypress:open を実行して Cypress を起動し、E2E テストスイートを実行します。

知っておくと良いこと

  • cypress.config.js 設定ファイルに baseUrl: 'https://:3000' を追加することで、cy.visit("https://:3000/") の代わりに cy.visit("/") を使用できます。
  • または、start-server-and-test パッケージをインストールして、Next.js 本番サーバーと Cypress を連携させて実行できます。インストール後、package.json の scripts フィールドに "test": "start-server-and-test start https://:3000 cypress" を追加します。新しい変更を行った後は、アプリケーションの再ビルドを忘れないでください。

初めての Cypress コンポーネント テストを作成する

コンポーネント テストでは、アプリケーション全体をバンドルしたりサーバーを起動したりすることなく、特定のコンポーネントをビルドしてマウントします。

Cypress アプリでコンポーネント テストを選択し、次にフロントエンド フレームワークとして Next.js を選択します。cypress/component フォルダがプロジェクトに作成され、cypress.config.js ファイルがコンポーネント テストを有効にするように更新されます。

cypress.config ファイルが次の構成になっていることを確認してください。

cypress.config.ts
import { defineConfig } from 'cypress'
 
export default defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})

前のセクションと同じコンポーネントを仮定して、コンポーネントが期待される出力をレンダリングしていることを検証するテストを追加します。

cypress/component/about.cy.js
import AboutPage from '../../pages/about'
 
describe('<AboutPage />', () => {
  it('should render and display expected content', () => {
    // Mount the React component for the About page
    cy.mount(<AboutPage />)
 
    // The new page should contain an h1 with "About page"
    cy.get('h1').contains('About')
 
    // Validate that a link with the expected URL is present
    // *Following* the link is better suited to an E2E test
    cy.get('a[href="/"]').should('be.visible')
  })
})

知っておくと良いこと:

  • Cypress は現在、async Server Components のコンポーネント テストをサポートしていません。E2E テストの使用をお勧めします。
  • コンポーネント テストでは Next.js サーバーは必要ないため、サーバーの利用に依存する <Image /> のような機能は、そのままでは機能しない場合があります。

コンポーネント テストを実行する

ターミナルで npm run cypress:open を実行して Cypress を起動し、コンポーネント テストスイートを実行します。

継続的インテグレーション (CI)

インタラクティブなテストに加えて、CI 環境に適した cypress run コマンドを使用して Cypress をヘッドレスで実行することもできます。

package.json
{
  "scripts": {
    //...
    "e2e": "start-server-and-test dev https://:3000 \"cypress open --e2e\"",
    "e2e:headless": "start-server-and-test dev https://:3000 \"cypress run --e2e\"",
    "component": "cypress open --component",
    "component:headless": "cypress run --component"
  }
}

Cypress と継続的インテグレーションの詳細については、これらのリソースをご覧ください。