Cypress を触ってみる

参考

インストール

npm install cypress

起動

npx cypress open

初期設定

ウィンドウが立ち上がるので下記の通り設定する。

  1. E2E Testing をクリックする。
  2. Continue をクリックする。
  3. Chrome をクリックする。
  4. Start E2E Testing in Chrome をクリックする。

階層

デフォルトでは下記のような階層が出来上がる。

.
├── cypress
│   ├── fixtures #(テストデータを入れるディレクトリ)
│   │   └── example.json
│   └── support #(cypressにカスタムコマンドを追加するディレクトリ)
│       ├── commands.js
│       └── e2e.js
└── cypress.config.js

テスト対象のファイルを作成

テスト対象のファイルを作成します。

.
├── cypress
│   ├── fixtures
│   │   └── example.json
│   └── support
│       ├── commands.js
│       └── e2e.js
├── cypress.config.js
└── hoge.html # これ

hoge.html の中身は下記の通り。

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8">
        <title>サンプル</title>
    </head>

    <body>
        <h1> 登録フォーム </h1>
        メールアドレス
        <input type="email" id="input-email"/>
        <p>権限
        <select id="select-role">
            <option value="一般">一般</option>
            <option value="管理者">管理者</option>
        </select></p>   

        <input type="button" value="登録" id="submit" onclick="Submit()"/>
        <p id='result-email'>未記入</p>
        <p id='result-role'>未記入</p>

        <script>
        function Submit() {
        document.getElementById('result-email').textContent =
            document.getElementById("input-email").value;

        document.getElementById('result-role').textContent =
            document.getElementById("select-role").value;
        }
        </script>
    </body>
</html>

テストコードを書くファイルを作成

テストコードを書くファイルを作成します。
ディレクトリ構成やファイル名は自由ですが、cypres のサンプルだと e2e 配下に作るみたいなのでとりあえず従います。

.
├── cypress
│   ├── e2e
│   │   └── spec.cy.js # これ
│   ├── fixtures
│   │   └── example.json
│   └── support
│       ├── commands.js
│       └── e2e.js
├── cypress.config.js
└── hoge.html

spec.cy.js の中身は下記の通り。

describe('template spec', () => {
  it('passes', () => {
    cy.visit('hoge.html') // テスト対象のファイルパス指定。(URL指定も可能。)
    cy.get('#input-email').type('dummy@email.com') // 入力。
    cy.get('#select-role').select('管理者') // 選択。
    cy.get('#submit').click() // ボタン押下。
    cy.get('#result-email').should('have.text', 'dummy@email.com') // 出力値テスト。
    cy.get('#result-role').should('have.text', '管理者')// 出力値テスト。
  })
})

実行

GUIで実行する

  1. Cypress のウィンドウにもどる。
  2. サイドバーの「Spec」をクリックする。
  3. 「cypress/e2e」内の[spec.cy.js]をクリックする。

CUIで実行する

全てのテストを実行する。

npx cypress run

ファイルを指定して一部のテストを実行する。

npx cypress run -s ./cypress/e2e/spec.cy.js

動画を確認する

CUIでテストを実行すると、動画を撮って保存してくれるみたいです。

.
├── cypress
│   ├── e2e
│   │   └── spec.cy.js
│   ├── fixtures
│   │   └── example.json
│   ├── support
│   │   ├── commands.js
│   │   └── e2e.js
│   └── videos
│       └── spec.cy.js.mp4 # これ
├── cypress.config.js
└── hoge.html

オプションで動画を残さないようにもできるようです。

npx cypress run -s ./cypress/e2e/spec.cy.js --config video=false
YouTube