7
9

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.

karma+mocha+chaiでnode上テスト開発最初の一歩

7
Last updated at Posted at 2014-05-18

参考になったのでリプ

達成すること:

  1. 設定を用意
  2. (テストしたいクラスとかメソッドがあるファイルを用意)
  3. テスト書く
  4. テスト実行 karma start
  5. ブラウザで結果が返ってくる!

npm install -g karma-cli

karmaコマンドが使えるようになった。npm install -g karmaだとエラーがよくおきるらしいので注意。
karma init でkarma.conf.jsっていう設定を作る。

$ karma init
「フレームワーク何?」> mocha + chai
「Require.js使わん?」 > no
「ブラウザ実行はどれでするん?」 > Chrome
「どこにソースとテストソースあるん?」 > *.js
「除外ファイルがあるならいってみ?(無言でスルー)」 >
「自動更新したい?」 > yes

フレームワークもってないから用意しなきゃいけない><(後述)
chromeはインストール済。
*.jsは**/*.jsとかも使える。

ソース場所をpackage.json やら node_modules のあるカレントディレクトリと指定してみた。指定されたjsが容赦なく読み込まれると考えていいので、名前空間にあるクラスとか、require.jsでまとまった名前空間とかを持ってきてテストする感じ。browserifyもある。

とりあえず今回は

hello.coffee
hello = () -> return "hello"

次にテスト用のjsを作る。
hello.jsのほかにも名前空間を汚染した分だけテスト用のjsで使える。

hello.test.coffee
describe "最初のテスト", () ->
  it "return hello してほしい!", () ->
    expect(hello()).to.equal("hello")

hello.coffee はbareコンパイルだから呼べる。
describe ~ とか it ~ とかがmocha の表現。

describe: 「このテストのテーマはこれです!!」
it: 「まず、〜〜が返ってきますよ、次に〜〜が返ってきますよ。」
テスト宣言系、年収高い系

expect ~ とか to.equal ~ が chai の表現。

expect(@@@): 主語
.to.equal(@@@): 述語系

mocha は 主語・述語系の機能を各自追加しないといけないってことです。
mocha chaiインストールしよう。

npm install -D karma-mocha
npm install -D karma-chai

ここでkarma.conf.js の中身を見ます。
frameworks: ['mocha', 'chai']
ってなってればおkです。

フォルダには
karma.conf.js
hello.js
hello.test.js
node_modules
があって、名前空間はhello.js テストはhello.test.jsにしか書かれてない状況なわけです。

karma start

サーバーが立ち上がって、指定のソースをすべて読むので、1つ成功と出ます。
自動更新onなので、変更を加えると更新してくれます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?