コンテンツへスキップ

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

手動設定

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

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

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

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

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')
  })
})

エンドツーエンドテストの実行

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アプリケーションで**コンポーネントテスト**を選択し、フロントエンドフレームワークとして**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.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`サーバーコンポーネントのコンポーネントテストをサポートしていません。E2Eテストを使用することをお勧めします。
  • コンポーネントテストではNext.jsサーバーは必要ないため、サーバーの可用性に依存する``などの機能は、すぐに動作しない場合があります。

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

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

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

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

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と継続的インテグレーションの詳細については、以下のリソースをご覧ください。