Ikkyu's Tech Blog

技術系に関するブログです。

TestCafeで簡単にE2Eのテストを行う

業務の休み時間に技術ブログを読むのが最近日課になっています。

そこで「TestCafe」というE2Eテストツールを見つけました。

とても簡単にテストを書けるみたいなので、少し触ってみました。
機能が多そうなので、少しずつ追記していきながら、紹介してこうかなと思います🙇‍♂️

前提としてNode.jsがインストールされているものとします。

TestCafeをインストール

公式を見るとnpm install -g testcafeとしてますが、グローバルに入れたくないのでローカルにインストールします。

npm install testcafe

その後、package.jsonのscriptsを変更します。

{
  ...,
  scripts: {
    "testcafe": "testcafe", // 追加
    ...
  }
}

npm run testcafeでtestcafeコマンドを実行できるようになりました。

色んなブラウザで実行してみる

実行するファイルを作成

touch firstTest.js

firstTest.jsの内容は公式に載っている以下のコード1を使用します。

import { Selector } from 'testcafe'; // first import testcafe selectors

fixture `Getting Started`// declare the fixture
    .page `https://devexpress.github.io/testcafe/example`;  // specify the start page


//then create a test and place your code there
test('My first test', async t => {
    await t
        .typeText('#developer-name', 'John Smith')
        .click('#submit-button')

        // Use the assertion to check if the actual header text is equal to the expected one
        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');
});

ブラウザ指定してを実行

対応しているブラウザ一覧は以下の通りです2

Chromeの場合

$ npm run testcafe chrome firstTest.js 
 Running tests in:
 - Chrome 75.0.3770 / Mac OS X 10.14.5

 Getting Started
(node:4193) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
 ✓ My first test


 1 passed (4s)

TypeScriptもサポートしているので、拡張子をTSに変えても実行できました。素晴らしい👏

以上です。Warningが気になりますので調べてなきゃと思います。 それにしても、とても簡単です。

TestCafeはいいぞ!