Menu

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

Cypressエンドツーエンド(E2E)テストとコンポーネントテストに使用されるテストランナーです。このページではNext.jsでCypressをセットアップし、最初のテストを書く方法を紹介します。

警告:

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

クイックスタート

with-cypress例を使用したcreate-next-appで素早く始めることができます。

Terminal
npx create-next-app@latest --example with-cypress with-cypress-app

手動セットアップ

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

Terminal
npm install -D cypress
# または
yarn add -D cypress
# または
pnpm install -D cypress

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

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

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

Terminal
npm run cypress:open

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

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

cypress.configファイルに次の設定があることを確認してください:

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

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

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

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

cypress.configファイルに次の設定があることを確認してください:

cypress.config.ts
TypeScript
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サーバーコンポーネントのコンポーネントテストをサポートしていません。E2Eテストの使用をお勧めします。
  • コンポーネントテストではNext.jsサーバーが不要なため、サーバーの利用を前提とする<Image />などの機能はそのままでは機能しない可能性があります。

コンポーネントテストの実行

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

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

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

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

CypressとCIについては以下のリソースから詳細を学ぶことができます: