コンテンツにスキップ

Next.jsでのCypressの設定方法

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

警告

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

クイックスタート

create-next-appwith-cypress example を使用すると、すぐに開始できます。

ターミナル
npx create-next-app@latest --example with-cypress with-cypress-app

手動セットアップ

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ファイルを作成します。

app/page.js
import Link from 'next/link'
 
export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
app/about/page.js
import Link from 'next/link'
 
export default function Page() {
  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.tsx
import Page from '../../app/page'
 
describe('<Page />', () => {
  it('should render and display expected content', () => {
    // Mount the React component for the Home page
    cy.mount(<Page />)
 
    // The new page should contain an h1 with "Home"
    cy.get('h1').contains('Home')
 
    // Validate that a link with the expected URL is present
    // Following the link is better suited to an E2E test
    cy.get('a[href="/about"]').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と継続的インテグレーションについてさらに詳しく学ぶことができます。