ページ

2013年6月16日日曜日

JavaScriptのテスト環境を整える その3

その1 その2

モジュール単位でファイル分割する。RequireJS使う。

前々回からのbower.jsonを編集。dependenciesにrequirejsを追加する。
{ "name": "zakuni-js-template", "version": "0.0.3", "main": "main.js", "ignore": [ "**/.*", "node_modules", "components" ], "dependencies": { "requirejs": "latest" }, "devDependencies": { "mocha": "latest", "chai": "latest" } }

色々と試行錯誤した結果、こうなった。
. ├── bower.json ├── camera.coffee ├── camera.js ├── components │   ├── chai │   ├── jquery │   ├── mocha │   └── requirejs ├── index.html ├── main.coffee ├── main.js └── test ├── test.camera.coffee ├── test.camera.js ├── test.coffee ├── test.html └── test.js
index.html用のメインと、テスト用のmainは別のファイルにする(main.jsとtest.js)。
あと、テストもモジュール単位で分ける(camera.jsのテストはtest.camera.jsを作るようにする)。
mocha.setupとかmocha.runはtest.jsで行う。

中身はこういう感じになっている。
define () ->
class Camera
take: ->
# do nothing
view raw camera.coffee hosted with ❤ by GitHub
define ['camera', 'mocha', 'chai'], (Camera, mocha, chai) ->
assert = chai.assert
suite 'Camera', () ->
camera = new Camera()
suite '#Camera', () ->
test 'is instance of Camera', () ->
assert.instanceOf(camera, Camera)
suite '#take()', () ->
test 'is function', () ->
assert.isFunction(camera.take)
requirejs.config
paths:
mocha: '../components/mocha/mocha'
chai: '../components/chai/chai'
camera: '../camera'
shim:
'mocha':
init: () ->
this.mocha.setup('tdd')
return this.mocha
require ['camera', 'mocha', 'chai', 'test.camera'], (Camera) ->
mocha.run()
view raw test.coffee hosted with ❤ by GitHub
<html>
<head>
<meta charset="utf-8">
<title>Mocha Tests</title>
<link rel="stylesheet" href="../components/mocha/mocha.css" />
</head>
<body>
<div id="mocha"></div>
<script src="../components/chai/chai.js"></script>
<script src="../components/mocha/mocha.js"></script>
<script src="../components/requirejs/require.js" data-main="test"></script>
</body>
</html>
view raw test.html hosted with ❤ by GitHub


https://github.com/zakuni/js-template/tree/v0.0.3
RequireJS使おうとしたら時間かかってしまって最終的にちゃんと整理しきれなかった感があるので、そのうちまたまとめ直すかもしれない(しないかもしれない)。

0 件のコメント:

コメントを投稿