ゴール
クライアントサイドJavaScriptの、とくにDOMとか触らない部分をnode.jsでテストするのがゴールです。バッドノウハウかもしれませんが、大げさな作業もいらないので、軽くやるくらいなら問題無いと思います。
前提条件
- npmインストール済
作業
まずプロジェクト作ります。
$ mkdir hello-node
$ cd hello-node
$ npm init
npm init
後対話形式でプロジェクトの設定を聞かれますが、連打して終わせます。次にtestするためにmocha
をnpm install --save mocha
でインストールします。すると、package.jsonは次のようになります。
{
"name": "hello-node",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"mocha": "^3.2.0"
}
}
npm test
でmochaがtestディレクトリにあるテストを実行するようにpackage.jsonを書き換えます。
@@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
- "test": "echo \"Error: no test specified\" && exit 1"
+ "test": "./node_modules/.bin/mocha test"
},
"author": "",
"license": "ISC",
test用のファイル`calc-test.js'をtestディレクトリに作ります。
var assert = require("assert");
describe("calc", function() {
it("add", function() { assert.equal(4, 1 + 3);});
it("sub", function() { assert.equal(3, 4 - 1);});
it("sub_", function() { assert.equal(2, 4 - 1);});
});
npm test
するとちゃんとテストが走って、次のように標準出力されます。
> mocha test
calc
✓ add
✓ sub
1) sub_
2 passing (7ms)
1 failing
1) calc sub_:
AssertionError: 2 == 3
+ expected - actual
-2
+3
testが実行できることが確認できました。ここでsrcディレクトリを作って、そこに最終的にクライアントサイドで使う予定のjsファイル(ファイル名はbird.js
)を作ります。
var Bird = function() {};
Bird.prototype.say = function() {
return "ka-ka-";
};
try { module.exports = Bird;} catch(e) {};
ブラウザにはmodule
なんて編集は定義されてないので、try-catchでエラーを黙らせます。それでは、これをテストするファイルbird-test.js
を作ります。
var assert = require("assert");
var Bird = require("../src/bird");
describe("animal", function() {
it("say", function() {
assert.equal("ka-ka-", new Bird().say());
});
});
npm test
すると、bird-test.js
で定義したテストも実行されて、次のように標準出力されます。
> mocha test
animal
✓ say
calc
✓ add
✓ sub
1) sub_
3 passing (7ms)
1 failing
1) calc sub_:
AssertionError: 2 == 3
+ expected - actual
最後にhello-node
ディレクトリ上に次のHTMLファイルを作ってブラウザで開きます。
<html>
<head>
<title>hello</title>
<script src="./src/bird.js"></script>
</head>
<body>
</body>
</html>
ディベロッパーツールのコンソールで動作することを確認します(画像はChrome)。
このときのディレクトリの構成は次のようになっています。
.
├── index.html
├── node_modules
│ └── mocha
├── package.json
├── src
│ └── bird.js
└── test
├── bird-test.js
└── calc-test.js