コンテンツへスキップ

Next.jsでのCypressの設定

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

警告

  • **コンポーネントテスト**の場合、現在CypressはNext.jsバージョン14および`async`サーバーコンポーネントをサポートしていません。これらの問題は現在追跡されています。現時点では、コンポーネントテストはNext.jsバージョン13で動作し、`async`サーバーコンポーネントにはE2Eテストを推奨します。
  • 13.6.3より前のCypressバージョンは、TypeScriptバージョン5と`moduleResolution:"bundler"`をサポートしていません。ただし、この問題はCypressバージョン13.6.3以降で解決されています。Cypress v13.6.3

クイックスタート

with-cypressの例を使用して`create-next-app`を使うと、すぐに開始できます。

ターミナル
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": "next lint",
    "cypress:open": "cypress open"
  }
}

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

ターミナル
npm run cypress:open

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

最初のCypress E2Eテストの作成

cypress.config.jsファイルに以下の設定を追加してください。

cypress.config.ts
import { defineConfig } from 'cypress'
 
export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})
cypress.config.js
const { defineConfig } = require('cypress')
 
module.exports = 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://127.0.0.1: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://127.0.0.1:3000'を追加することで、cy.visit("https://127.0.0.1:3000/")の代わりにcy.visit("/")を使用できます。
  • または、start-server-and-testパッケージをインストールして、Next.js本番サーバーとCypressを連携して実行することもできます。インストール後、package.jsonのscriptsフィールドに"test": "start-server-and-test start https://127.0.0.1:3000 cypress"を追加します。変更を加えた後は、アプリケーションを再ビルドすることを忘れないでください。

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

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

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

cypress.config.jsファイルに以下の設定を追加してください。

cypress.config.ts
import { defineConfig } from 'cypress'
 
export default defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})
cypress.config.js
const { defineConfig } = require('cypress')
 
module.exports = 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サーバーは必要ないため、サーバーの可用性に依存する``などの機能はすぐに動作しない場合があります。

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

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

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

対話型テストに加えて、CI環境に適したヘッドレスモードでcypress runコマンドを使用してCypressを実行することもできます。

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

Cypressと継続的インテグレーションの詳細については、以下のリソースを参照してください。