7
8

More than 5 years have passed since last update.

Docker + WebDriverIO + Chrome headlessでお手軽E2Eテスト

Last updated at Posted at 2017-12-06

こんにちは、E2Eテストしてますか?
実際どのくらいの人がテストしてるんでしょうね。
何を使ってるんでしょうね。

自分は以下のポイントを重視して、 WebdriverIO + Mocha + Chai を選択してます
- テストの書きやすさ
- Chrome headlessを簡単に使える
- CLIで動作する

CircleCIなどと連携しておけば完璧ですね!

とりあえず動かしたい

簡単に動かすなら Docker ですね!
準備してみました。
ちょっとサイズ大きめです。。。

docker pull skozo/webdriverio-chrome-headless

webdriverio-chrome-headless

実行準備

必要なファイル群を設置します。

node_modules などを取得するので、適当なディレクトリで以下のコマンドを実行してください。

docker run -it --rm -v $(pwd):/app skozo/webdriverio-chrome-headless init

出てくる選択肢は以下をとりあえず選んでおいてください。

? Where do you want to execute your tests? (Use arrow keys)
❯ On my local machine

? Which framework do you want to use? (Use arrow keys)
❯ mocha

? Shall I install the framework adapter for you? (Y/n)
❯ Y

? Where are your test specs located? (./test/specs/**/*.js)
❯ ./test/specs/**/*.js

? Which reporter do you want to use?
❯ dot

? Do you want to add a service to your test setup?
❯ selenium-standalone

? Level of logging verbosity (Use arrow keys)
❯ silent

? In which directory should screenshots gets saved if a command fails? 
❯ ./errorShots/

? What is the base url?
❯ http://localhost

テストコード用ディレクトリの作成

Where are your test specs located? で入力したディレクトリを作成しておいてください

mkdir -p test/specs

テストコード用ファイルの作成

テストコード用ディレクトリに jsファイルを設置してください。

touch test/specs/main.js
// サンプル
var assert = require('assert')
var should = require('chai').should();

describe('example page', function() {
  it('example', function() {
    // トップページ
    browser.url('http://example.com')
    title = browser.getTitle()
    title.should.equal('Example Domain')

    browser.saveScreenshot('example.png');
  })
})

設定ファイルの編集

WebdriverIOのデフォルトではFirefoxを利用してテスト実行するように設定されてます。
Chromeに変更しましょう

capabilities という項目があるので、以下に置き換えてください

wdio.conf.js
    capabilities: [{
        maxInstances: 5,
        browserName: 'chrome',
        chromeOptions: {
            args: ['--headless', '--disable-gpu', '--no-sandbox', '--window-size=1920,1080'],
        }
    }],

いざ!テスト実行!

docker run -it --rm --cap-add=SYS_ADMIN --shm-size=128m -v $(pwd):/app skozo/webdriverio-chrome-headless wdio

1 passing と表示されて、ディレクトリに example.png が出力されていればOK!

その他

テストこけたときに自動的にScreenshotを保存したい!
以下のようなコードを書きます

wdio.conf.js
    afterTest: function (test) {
        if (test.passed) {
            return;
        }
        var filename = encodeURIComponent(test.title.replace(/\s+/g, '-'));
        var filePath = this.screenshotPath + filename + '.png';
        browser.saveScreenshot(filePath);
    },

いいテストライフを!

7
8
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
7
8