LoginSignup
11

More than 5 years have passed since last update.

Node.js+Coffeescript+MochaをTravis.ci上で動かす

Last updated at Posted at 2014-07-13

(chaiとsinonも使ってます)

概要

Node.js+Coffeescriptで書いている際に、
Mochaを使ってテストをする方法が
ちょっと調べないとわからない感じだったのでまとめました。

Node.jsでテストする

必要なものをpackege.jsonに書く

package.jsonのscript部分にテストするためのコマンドを、
devDependencies部分にテストだけで使うライブラリを書いていきます。
なお、テスト設定等はCakefileに書きます

{
  "scripts": {
    "test": "cake test"
  },
  "dependencies": {
    "coffee-script": ">= 1.1.0"
  },
  "devDependencies": {
    "chai": "~1.0.3",
    "mocha": "~1.1.0",
    "sinon": "~1.10.2"
  }
}

Cakefileの設定

以下のように書きます。
テストの出力方法を変えたい場合は、
REPORTER部分を後述するmochaの設定を参考にして適当に変えてください。

{exec} = require "child_process"

REPORTER = "spec"

task "test", "run tests", ->
  exec "NODE_ENV=test
    ./node_modules/.bin/mocha
    --compilers coffee:coffee-script/register
    --reporter #{REPORTER}
    --require coffee-script
    --require test/test_helper.coffee
    --colors
  ", (err, output) ->
    throw err if err
    console.log output

出典

なお、リンク元では古い書き方
--compilers coffee:coffee-scriptだったため、
--compilers coffee:coffee-script/registerに変更してます。

テスト時に共通で読み込むファイル作成

chaiとsinonを両方requireする必要がありますが、
毎回書くのは大変なので、Cakefileで
--require test/test_helper.coffeeと指定し、
このファイルにrequireを書きます。

global.assert = require("chai").assert
global.sinon = require('sinon')

テストを書く

testフォルダにファイルを置いてテストを書いていきます

User = require('../src/scripts/user.coffee').User

describe "test", ->
  name = undefined
  beforeEach (done) ->
    name = "testuser"
    done()

  it 'set date', (done)->
    name = new User name
    assert.equal user.name, name
    done()

テストする

npm test
でテストできます

Travis.ciでテストする

テスト用設定ファイルの作成

Travis.ciの設定の為に、ルートフォルダに.travis.ymlを作ります。
node用の設定は以下のようになります。

language: node_js
node_js:
  - "0.10"

Travis CI: Building a Node.js project

これで、Travis.ciが指定したバージョンで
npm testを利用してテストをしてくれます。

また、node_jsの下にテストしたいバージョンを列挙すると、
その全てでテストをしてくれます。

便利(`・∀・´≡`・∀・´)

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
11