Skip to content

Instantly share code, notes, and snippets.

@aita
Last active December 18, 2015 00:39
Show Gist options
  • Save aita/5698043 to your computer and use it in GitHub Desktop.
Save aita/5698043 to your computer and use it in GitHub Desktop.
QUnitとPhantomJSによるテストの方法

PhantomJSとQUnitによる自動テスト

JavaScriptをテストするのに、テストフレームワークとして、 QUnitを使い、PhantomJSでコンソールでテストできるようにした。

QUnitによるブラウザテスト

PhantomJSでQUnitを動かす前に、まずはブラウザで動かしてみる。

http://qunitjs.com/ から、qunit.js, qunit.cssの最新を落とす。

2013/06/03では、以下のファイルが最新だった。

  • qunit-1.11.0.js
  • qunit-1.11.0.css

それぞれ、qunit.js, qunit.cssにリネームしてディレクトリに配置する。

テストを実行するためのHTMLファイルを用意する。

index.html

<html>
<head>
<meta charset="utf-8">
<title>QUnit Example</title>
<link rel="stylesheet" href="qunit.css">
<script src="qunit.js"></script>
<script src="tests.js"></script>
</head>
<body>
<div id="qunit"></div>
<div id="qunit-fixture"></div>
</body>
</html>

そして、テストを記述するファイルを用意。

tests.js

test( "hello test", function() {
ok( 1 == "1", "Passed!" );
});

index.htmlをブラウザで開くとテストが実行され、以下の様な結果が出力されるはず。

Tests completed in 75 milliseconds.
1 assertions of 1 passed, 0 failed.

PhantomJSの導入

ここまでのテストを、PhantoJSで実行させる。

OSXの場合は、実行バイナリがサイトにあるので、これを使う。 http://phantomjs.org/ からZIPをダウンロード。

npm や macports からもインストールできるが、 OSXの場合、実行バイナリを落として使うのが一番楽。

Linuxの場合は、素直にパッケージシステムでインストールするべき。

Ubuntuの場合

sudo aptitude install phantomjs

ダウンロードしたZIPの中に、examples/run-qunit.jsというファイルがあるので、 QUnitのディレクトリにコピーして、PhantomJSでQUnitを実行するために使う。

QUnitのレポジトリに、addons/phantomjs/runner.js というファイルがあるが、 試したところ、実行されたテストの数がおかしかったので使わないことにした。

ZIPをダウンロードしなかった場合は、 https://github.com/ariya/phantomjs/blob/master/examples/run-qunit.js からダウンロード出来る。

テストの実行

QUnitを配置したディレクトリでコマンドを実行

$ phantomjs run-qunit.js index.html

すると、以下の様な結果が出力されるはず

'waitFor()' finished in 200ms.
Tests completed in 15 milliseconds.
1 assertions of 1 passed, 0 failed.

TODO

  • テスト結果をマシなものにする(あまりに貧相なので)
  • RequireJSを使うケース
  • カバレッジの出力
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment