Murayama blog.

プログラミング教育なブログ

PhantomJS入門 CasperJSでテストする

CasperJSは、JavaScriptで実装されたPhantomJSのユーティリティです。PhantomJSを使ったFunctional Testを実行することができます。
CasperJS, a navigation scripting and testing utility for PhantomJS | CasperJS 1.0.2

はてなブログ(murayama blog)をテストしてみる

テストの題材として、
き、気がつけば使っていたChrome拡張機能 オススメ3つ - Murayama blog.
を扱うことにします。*1

さて、上記のページは以下のように構成されています。

  • タイトル:き、気がつけば使っていたChrome拡張機能 オススメ3つ
  • 見出し: 縦長画面もキャプチャできる - Screen Capture (by Google)
  • 見出し: 検索結果を1年以内のものにしてくれる - ato-ichinen
  • 見出し: SPDY! - SPDY indicator

さらにページのフッターには、"前の記事"というリンクがあります。
このリンクをクリックすると、前回の記事「PhantomJS入門 CasperJSを使う」が表示されまう。この記事は、

  • タイトル:PhantomJS入門 CasperJSを使う
  • 見出し: CasperJS
  • 見出し: Installation
  • 見出し: QuickStart
  • 見出し: ナビゲーションステップ

で構成されています。

今回はこの2つのページ構成(タイトルと見出し)を検証してみます。

テストコード

casper = require('casper').create();

casper.start 'http://murayama.hatenablog.com/entry/2013/07/05/183618', ->
    @capture "top.png"
    @test.assertTitle 'き、気がつけば使っていたChrome拡張機能 オススメ3つ - Murayama blog.', 'top page title is the one expected'
    @test.assertTextExists 'ato-ichinen', 'ato-ichinen extension exists'
    @test.assertTextExists 'Screen Capture (by Google)', 'Screen Capture (by Google) extension exists'
    @test.assertTextExists 'SPDY indicator', 'SPDY indicator exists'
    @click("a[rel=prev]")

casper.then ->
    @capture "prev.png"
    @test.assertTitle 'PhantomJS入門 CasperJSを使う - Murayama blog.', 'prev title is the one expected'
    @test.assertTextExists 'CasperJS', 'casperjs header exists'
    @test.assertTextExists 'Installation', 'Installation exists'
    @test.assertTextExists 'Quickstart', 'Quickstart exists'
    @test.assertTextExists 'ナビゲーションステップ', 'navigation step exists'

casper.run ->
    @test.done 9
    @test.renderResults true

CasperJSには、Tester-APIが提供されています。
URLや、ステータスコードを解析したり、レスポンスボディを検証したりすることができます。
http://casperjs.org/api.html#tester

今回のテストでは、startメソッドのコールバックで、
トップページにアクセスしたのち、スクリーンキャプチャの取得後、タイトルと見出しを検証しています。*2その後、前の記事リンクをクリックしています。

前の記事がレンダリングされると、thenメソッドのコールバックが実行されます。ここでもスクリーンキャプチャ取得後、ページのタイトル、見出しを検証しています。

最後にcasper.runメソッドを呼び出すことで、プログラムの実行を開始しています。runメソッドのコールバックでは、テスト件数と、テスト結果を示すよう指示しています。

テストの実行

casperjsコマンドで実行します。
テストの実行結果はカラーリングされて出力されます。

テスト結果をxUnitフォーマットで出力する

テスト結果をXMLフォーマットで出力することができます。JenkinsのようなCI環境で利用することもできます。

casper.run ->
    @test.done 9
    @test.renderResults true, 0, 'log.xml'

*1:先日まとめたChrome拡張の紹介記事です。こういうのって喜ばれるのかなーと思って書いてみましたが、、たいした反応もなく意気消沈気味です。

*2:assertTextExistsメソッドはテキストの有無を検証します。ちょっと雑なテストかも。