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 cypressCypressのopenコマンドをpackage.jsonのscriptsフィールドに追加します。
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "cypress:open": "cypress open"
  }
}Cypressを初めて実行して、Cypressテストスイートを開きます。
npm run cypress:openE2Eテストまたはコンポーネントテスト、あるいはその両方を設定できます。これらのオプションのいずれかを選択すると、プロジェクトにcypress.config.jsファイルとcypressフォルダーが自動的に作成されます。
最初のCypress E2Eテストの作成
cypress.configファイルに以下の設定があることを確認してください。
import { defineConfig } from 'cypress'
 
export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})次に、新しいNext.jsファイルを2つ作成します。
import Link from 'next/link'
 
export default function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}import Link from 'next/link'
 
export default function About() {
  return (
    <div>
      <h1>About</h1>
      <Link href="/">Home</Link>
    </div>
  )
}ナビゲーションが正しく機能しているか確認するためのテストを追加します。
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サーバーが実行されている必要があります。アプリケーションの動作により近い状態でテストを実行するために、本番コードに対してテストを実行することをお勧めします。
Next.jsアプリケーションをビルドするにはnpm run build && npm run startを実行し、その後、別のターミナルウィンドウでnpm run cypress:openを実行してCypressを起動し、E2Eテストスイートを実行します。
知っておくと良いこと
cypress.config.js設定ファイルにbaseUrl: 'https://:3000'を追加することで、cy.visit("https://:3000/")の代わりにcy.visit("/")を使用できます。- または、
start-server-and-testパッケージをインストールして、Cypressと連携してNext.js本番サーバーを実行することもできます。インストール後、package.jsonのscriptsフィールドに"test": "start-server-and-test start https://:3000 cypress"を追加してください。新しい変更を加えてからアプリケーションを再ビルドすることを忘れないでください。
最初のCypressコンポーネントテストの作成
コンポーネントテストは、アプリケーション全体をバンドルしたりサーバーを起動したりすることなく、特定のコンポーネントをビルドしてマウントします。
CypressアプリでComponent Testingを選択し、フロントエンドフレームワークとしてNext.jsを選択します。プロジェクトにcypress/componentフォルダーが作成され、cypress.config.jsファイルが更新され、コンポーネントテストが有効になります。
cypress.configファイルに以下の設定があることを確認してください。
import { defineConfig } from 'cypress'
 
export default defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})前のセクションと同じコンポーネントを仮定して、コンポーネントが期待される出力をレンダリングしていることを検証するテストを追加します。
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サーバーコンポーネントのコンポーネントテストをサポートしていません。E2Eテストの使用をお勧めします。- コンポーネントテストはNext.jsサーバーを必要としないため、サーバーが利用可能であることを前提とする
<Image />のような機能は、そのままでは動作しない場合があります。
コンポーネントテストの実行
ターミナルでnpm run cypress:openを実行してCypressを起動し、コンポーネントテストスイートを実行します。
継続的インテグレーション (CI)
対話型テストに加えて、cypress runコマンドを使用してCypressをヘッドレスで実行することもできます。これはCI環境に適しています。
{
  "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と継続的インテグレーションの詳細については、以下のリソースを参照してください。
お役に立ちましたか?