Setting up Cypress with Next.js
Cypress は、End-to-End (E2E)テストおよびComponent testing用のテストランナーです。このページでは、Cypress を Next.js と設定し、最初のテストを書く方法を示します。
警告:
- component テストについて、Cypress は現在 Next.js version14 と
asyncServer Components をサポートしていません。これらの問題は追跡中です。現在、component テストは Next.js version13 で動作し、asyncServer Components については E2E テストを推奨しています。- "現在、Cypress は
moduleResolution:"bundler"を伴うTypeScript version 5 をサポートしていません。この問題は追跡中です。
Manual setup
手動で Cypress を設定するには、cypressを dev の依存関係としてインストールします:
npm install -D cypress
# or
yarn add -D cypress
# or
pnpm install -D cypress
package.jsonの scripts フィールドに Cypress のopenコマンドを追加します:
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "cypress:open": "cypress open"
  }
}
初めて Cypress を実行して、Cypress テストスイートを開きます。
npm run cypress:open
E2E テストと/またはComponent テストを設定することを選択できます。これらの options のいずれかを選択すると、自動的にcypress.config.jsファイルとcypressフォルダがプロジェクトに作成されます。
Creating your first Cypress E2E test
cypress.config.js ファイルが次の設定を持っていることを確認してください:
import { defineConfig } from 'cypress'
export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})
const { defineConfig } = require('cypress')
module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})
それから、二つの新しい Next.js ファイルを作成してください:
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>
  )
}
あなたのナビゲーションが正しく動作しているか確認するために、test を追加してください:
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 server を稼働させる必要があります。アプリケーションの動作をより正確に再現するために、テストは production code に対して実行することをお勧めします。
npm run build && npm run startを実行して、あなたの Next.js アプリケーションを build してから、別のターミナル window でnpm run cypress:openを実行して、Cypress を start し、E2E テストスイートを実行してください。
Good to know:
cypress.config.js設定ファイルにbaseUrl: 'http://localhost:3000'を追加することで、cy.visit("http://localhost:3000/")の代わりにcy.visit("/")を使用することができます。- あるいは、
start-server-and-testパッケージをインストールして、Next.js production server を Cypress と一緒に実行することもできます。インストール後、"test": "start-server-and-test start http://localhost:3000 cypress"をあなたのpackage.jsonの scripts フィールドに追加してください。新しい変更後はアプリケーションを再構築することを忘れないでください。
Creating your first Cypress component test
Component テストは、アプリケーション全体をバンドルしたり、start を使って server を起動したりせずに、特定の component を build し、マウントします。
Cypress app でComponent Testingを選択し、次にフロントエンドフレームワークとしてNext.jsを選択します。プロジェクトにcypress/componentフォルダが作成され、cypress.config.jsファイルが更新されて component のテストが可能になります。
cypress.config.js ファイルが次の設定を持っていることを確認してください:
import { defineConfig } from 'cypress'
export default defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})
const { defineConfig } = require('cypress')
module.exports = defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})
前のセクションと同じコンポーネントを仮定し、 test を追加して、 component が期待される出力をレンダリングしていることを検証します:
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')
  })
})
Good to know:
- Cypress は現在、
asyncによる Server Components の component テストをサポートしていません。E2E テストの使用をお勧めします。- component テストは、Next.js server を require しないため、
<Image />のように server が利用可能であることに依存する機能は、初期設定のままでは機能しないかもしれません。
Component テストの実行
npm run cypress:openをターミナルで実行して、start Cypress を始動し、component テストスイートを実行してください。
Continuous Integration (CI)
インタラクティブなテストに加えて、cypress run コマンドを使用して、Cypress をヘッドレスで実行することも可能で、これは CI 環境により適しています。
{
  "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 と Continuous Integration についてさらに学ぶことができます: