0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Cypress】ReactアプリをE2Eテストする方法

Last updated at Posted at 2025-11-06

🧩 1. Cypressとは?

Cypress は、WebアプリのE2Eテストを簡単に自動化できるモダンなテストフレームワークです。
ブラウザ上で実際にアプリを操作しながらテストでき、React・Next.js・Vueなどに幅広く対応しています。

特徴:

UIを直接操作して動作確認が可能
スナップショットによる可視化
TypeScript対応
CI/CDパイプラインとの統合が容易

⚙️ 2. Cypressの導入手順

インストール

プロジェクトのルートで以下を実行します:

# Cypress本体をインストール
npm install --save-dev cypress

初期セットアップ

インストール後、初回セットアップを行います:

npx cypress open

これにより cypress/ ディレクトリが自動生成されます:

cypress/
  ├── e2e/
  │   └── example.cy.ts     # サンプルテスト
  ├── fixtures/
  ├── support/
  │   ├── commands.ts
  │   └── e2e.ts
cypress.config.ts

🧱 3. Cypressの基本構成

cypress.config.ts

生成された設定ファイルをTypeScriptで編集できます。
Reactアプリ(例えばViteやCRAなど)をローカルで起動してテストする場合、ベースURLを指定します:

cypress.config.ts
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:5173', // 開発サーバーのURL
    supportFile: 'cypress/support/e2e.ts',
  },
})

🧪 4. サンプルテストを作ってみよう

例:トップページの表示テスト

cypress/e2e/home.cy.ts を作成して、以下のように記述します。

cypress/e2e/home.cy.ts
describe('Home Page', () => {
  it('トップページが正しく表示される', () => {
    cy.visit('/')
    cy.contains('ようこそ') // ページ内に「ようこそ」が含まれているか確認
  })
})

🚀 5. テストの実行方法

① GUIモード(開発中に便利)

npx cypress open

② CLIモード(CI/CDで利用)

npx cypress run

🔧 6. TypeScript対応について

CypressはTypeScriptをサポートしています。
すでに.tsxを使っているなら、tsconfig.cypress.json を新規作成して以下を追加しておくと便利です:

tsconfig.cypress.json
{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["dom", "esnext"],
    "types": ["cypress"],
    "isolatedModules": false
  },
  "include": ["cypress/**/*.ts"]
}

tsconfig.json
{
  "files": [],
  "references": [
    { "path": "./tsconfig.app.json" },
    { "path": "./tsconfig.node.json" },
    { "path": "./tsconfig.cypress.json" },//  Cypress用を明示
  ]
}

🧠 7. Reactコンポーネント単体をテストしたい場合

E2E(ブラウザ操作)ではなく、コンポーネント単位のテスト もCypressで可能です。

npx cypress open --component

例:Buttonコンポーネントのテスト

sample.tsx
import React from 'react'
import Button from '../../src/components/Button'

describe('<Button />', () => {
  it('クリックできる', () => {
    cy.mount(<Button label="送信" />)
    cy.contains('送信').click()
  })
})

サイト

Selenium

Playwright

Cypress

CypressとPlaywrightとの比較

Vitestのコードカバレッジ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?