18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascriptのテストを自動化する

Last updated at Posted at 2016-04-07

前回jsのテストコードを作りましたが、これではいちいちhtmlを開かないと結果を確認できないので面倒。

そこで、ちょっと手を加えてコマンドラインからテストを実行し、ソースに変更があれば都度テストをし直すようにします。

ディレクトリ構成

基本は前回と同じですが、gulpを使うのでgulpfile.jsを追加

project_root/
├-node_modules
├-public
|  └-js
|     └sample.js
├-tests
|  └sample.test.html
├-gulpfile.js
└-package.json

パッケージインストール

追加するのは下記

  • gulp
  • phantomjs(コマンドラインから操作するブラウザ)
  • gulp-mocha-phantomjs(gulpからphantomjsを使うプラグイン)

npm install gulp phantomjs gulp-mocha-phantomjs --save-dev

個人的にグローバルインストールは極力避けたいので-gはつけません

package.json修正

とはいえこのままだとgulpコマンドが使えないので、package.jsonにscriptに追記します

package.json
{ 
  //省略
  "scripts": {
    "gulp": "gulp"
  },
  //省略

これでプロジェクトディレクトリ内ならnpm run gulpでgulpが動きます

gulpfile作成

次にgulpfileにタスクを書きます
起動時にまずテストして、その後ソースが変更されるたびにテストし直します

gulpfile.js
var gulp = require('gulp');
var mochaPhantomJS = require('gulp-mocha-phantomjs');

gulp.task("serve", ["test"],function(){
  //ソースが変更されたらテスト実行
  gulp.watch(["public/js/sample.js"], ["test"]);
});

gulp.task("test", function(){
  return gulp.src(["tests/sample.test.html"], {read:false})
      .pipe(mochaPhantomJS());
});

gulp.task("default", ["serve"]);

テスト実行

コマンドはnpm run gulp
スクリーンショット 2016-04-07 21.54.25.png

テストが実行されました。

試しにソースを書き換えると
スクリーンショット 2016-04-07 21.57.04.png

若干タイムラグはあるものの自動で再テスト
バグの早期発見に役立ちます

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?