LoginSignup
7

More than 3 years have passed since last update.

posted at

updated at

Seleniumで自動テスト

SeleniumでWebブラウザを使った自動テストが作成できます。
プログラムで作成する方法とノンプログラムでやる方法があります。

ノンプログラム方式

Selenium IDEというブラウザの操作をスクリプトに自動記憶させ、それを再生する事で自動テストを行います。
このやり方だと自由度が低く、効率的な運用には即さないです。
プログラムが書けない場合には有効だとは思います。

プログラム方式

SeleniumからWebDriverというライブラリが提供されています。下記の4言語が公式です。
- Java
- Javascript
- C#
- Python

この公式ライブラリとテストフレームワークを組み合わせて、自動テストを作成します。
自由度も高く、効率的な運用ができます。

WebDriverに「Javascript」、テストフレームワークに「mocha」を使ったサンプルを書いておきます。

環境構築

nvm と nodeをインストールします。

必要なライブラリインストール

javascriptのWebDriverをインストールします。
テストフレームワークとして使うmochaとexpectを使います。
mochaにはアサーション機能がないので、expectも使います。

npm -g install selenium-webdriver
npm install mocha
npm install expect.js

package.json作成

npm init

ChromeDriverをインストール

Chromeを使ったサンプルなので、ChromeDriverをインストールします。
ChromeDriver

サンプルソース実装

var webdriver = require('selenium-webdriver');
var expect = require('expect.js');
var assert = require('assert');
var By = webdriver.By;

describe('test sample', function(){
    this.timeout(15000);

    let browser;

    // テスト開始前に行う処理
    before(() => {
        browser = new webdriver.Builder().forBrowser('chrome').build();
    });

    // テスト終了時に行う処理
    after(() => {
        browser.quit();
    });

    // テスト内容(itを複数記述できる)
    it('web app test1 success', async function() {
        // googleホームページを起動する。
        await browser.get('https://google.co.jp');

        //テスト処理
        let targetValue = await browser.getTitle();
        expect(targetValue).to.be('Google');
    });

    it('web app test2 error', async function() {
        // googleホームページを起動する。
        await browser.get('https://google.co.jp');

        //テスト処理
        let targetValue = await browser.getTitle();
        expect(targetValue).to.be('Google111');
    });
});

サンプル実行

npm test sample.js

これでブラウザが起動し、タイトルが「Google」かチェックし、その結果が標準出力されます。

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
What you can do with signing up
7