LoginSignup
3
6

More than 5 years have passed since last update.

ChromeとFireFoxのHeadless機能を使ってブラウザーテスト駆動開発[gulp+karma+jasmine&GitHub+TravisCI]

Posted at

少し遅れましたが、Chromeがヘッドレスブラウザを立ち上げることができるようになったので
ブラウザーテスト駆動を導入してみました。

ローカル環境

mac(macOS 10.13.6)
Node.js(8.9.3)
gulp(3.9.1)
karma(2.0.0)

バージョン管理

GitHub
TravisCI

ローカル環境の準備

1. Node.jsの導入

nvmでNode.jsは管理する

cd ~
git clone https://github.com/creationix/nvm.git ~/.nvm
source ~/.nvm/nvm.sh
nvm install v8.9.3
nvm alias default v8.9.3

macを起動した時に自動でNode.jsが起動するよう設定

vim ~/.bash_profile

下記を追記

[[ -s ~/.nvm/nvm.sh ]] && . ~/.nvm/nvm.sh
nvm use default
npm_dir=${NVM_PATH}_modules
export NODE_PATH=$npm_dir

反映して完了

source ~/.bash_profile

2. gulp & karma

npm install -g gulp karma

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

npm install browser-sync gulp gulp-concat gulp-uglify jasmine jasmine-core karma karma-chrome-launcher karma-coverage karma-firefox-launcher karma-jasmine karma-spec-reporter --save-dev

3. gulpfile.jsを設定

gulpfile.js
var gulp    = require("gulp");
var browser = require("browser-sync").create();
var concat  = require("gulp-concat");
var uglify  = require("gulp-uglify");
var Server  = require("karma").Server;

/**
 * server setting
 */
gulp.task("server", function ()
{
    browser.init({
        server: {
            baseDir: "./",
            index: "index.html"
        }
    });
});

/**
 * browser reload
 */
gulp.task("reload", function ()
{
    browser.reload();
});

/**
 * output js file
 */
gulp.task("output", function ()
{
    gulp.src([
            "src/**/*.js"
        ])
        .pipe(concat("output.js")) // 複数のJSを一個にまとめる
        .pipe(uglify()) // 圧縮
        .pipe(gulp.dest(".")); // 圧縮したファイルを出力
});

/**
 * default setting
 */
gulp.task("default", ["server"], function ()
{
    gulp.watch(["src/**/*.js"], ["tdd"]);
    gulp.watch(["output.js"], ["reload"]);
});

/**
 * test-driven development
 */
gulp.task("tdd", function (done)
{
    new Server({
        configFile: __dirname + "/karma.conf.js",
        singleRun: false
    }, done)
        .on("run_complete", function (browsers, results)
        {
            if (results.failed) {
                throw new Error("failed");
            }
            gulp.start.apply(gulp, ["output"]);
        })
        .on("error", function (err) {
            done(err);
        })
        .start();
});

/**
 * Run test once and exit
 */
gulp.task("test", function (done)
{
    new Server({
        configFile: __dirname + "/karma.conf.js",
        singleRun: true
    }, done).start();
});

4. karma.conf.jsを設定

karma.conf.js
// Karma configuration
// Generated on Wed Sep 06 2017 20:07:29 GMT+0900 (JST)

module.exports = function(config)
{
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
        "src/**/*.js",
        "test/**/*.js"
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
        'src/**/*.js': ['coverage']
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['spec', 'coverage'],


    coverageReporter: {
      type: 'html',
      dir: 'coverage/'
    },


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeHeadless', 'FirefoxHeadless'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,


    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  });
};

これで、ローカルの準備が整ったのでgulpを起動して動くか確認。

[00:00:00] Using gulpfile ~/gulpfile.js
[00:00:00] Starting 'server'...
[00:00:00] Finished 'server' after 8.89 ms
[00:00:00] Starting 'default'...
[00:00:00] Finished 'default' after 184 ms
[Browsersync] Access URLs:
 --------------------------------------
       Local: http://localhost:3000
    External: http://192.168.***.***:3000
 --------------------------------------
          UI: http://localhost:3001
 UI External: http://192.168.***.***:3001
 --------------------------------------
[Browsersync] Serving files from: ./

TravisCIの設定

1. .travis.yml

.travis.yml
language: node_js
node_js:
  - "8.9.3"

cache:
  directories:
    - "node_modules"

sudo: required
addons:
  chrome: stable
  firefox: latest

before_install:
  - npm install -g gulp karma

install:
  - npm install

before_script:
  - "export CHROME_BIN=chromium-browser"
  - "export DISPLAY=:99.0"
  - "sh -e /etc/init.d/xvfb start"
  - sleep 3

2. package.json

package.json
{
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "gulp test"
  }
}

これで完了、ローカルではファイルを変更時に、コミット後はTravisCIで自動テスト

ブラウザテストできるのは助かる

3
6
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
3
6