日々精進

新しく学んだことを書き留めていきます

mochaでファイル単位でテストを実行する方法

2013-05-02 - 日々精進で紹介した方法をアレンジしてファイル単位で
テストを実行できるようにした。
あとsearch pathを設定する方法 - 日々精進のsearch pathを設定する方法も使ってテストファイル内でもrequire "hoge"できるようにした。
mocha.coffeeを↓のような感じで書いて

Mocha = require('mocha')
require "should"
require "long-stack-traces"
path = require "path"
fs = require "fs"
file = require "file"
_ = require "underscore"
opts = require "opts"
require("../init-search-path").initSearchPath()

opts.parse [
  'short': 't',
  'long': 'target',
  'description': 'test case file to run',
  'value': true,
  'required': false
]

TESTS_PATH = "tests/sources/"
mocha = new Mocha

file.walkSync TESTS_PATH, (dirPath, dirs, files) ->
  testJsFiles = _.filter files, (file) ->
    targetFileName = opts.get('target')
    isTarget = targetFileName == undefined || file.indexOf(opts.get('target')) != -1
    return file.substr(-3) == '.js' && isTarget

  _.each testJsFiles, (file) ->
    mocha.addFile(path.join(dirPath, file))

mocha.timeout = 5000

runner = mocha.run ->
  console.log('finished')
  process.exit()

runner.on 'pass', (test) ->
  console.log('... %s passed', test.title)

runner.on 'fail', (test) ->
  console.log('... %s failed', test.title)

webstormの設定を↓のようにする。

理想はProjectツリーやエディタで右クリック→テスト実行だけど、ちょっと近付いたかな。
てかもっといい方法あるよなぁ、絶対。。