LoginSignup
3
5

More than 5 years have passed since last update.

クライアントサイドJSをnode.jsでテストする

Last updated at Posted at 2017-03-21

ゴール

クライアントサイドJavaScriptの、とくにDOMとか触らない部分をnode.jsでテストするのがゴールです。バッドノウハウかもしれませんが、大げさな作業もいらないので、軽くやるくらいなら問題無いと思います。

前提条件

  • npmインストール済

作業

まずプロジェクト作ります。

$ mkdir hello-node
$ cd hello-node
$ npm init

npm init後対話形式でプロジェクトの設定を聞かれますが、連打して終わせます。次にtestするためにmochanpm 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)。
d2f26ccd39c9624aaba1fe8479a98b5c.png
このときのディレクトリの構成は次のようになっています。

.
├── index.html
├── node_modules
│   └── mocha
├── package.json
├── src
│   └── bird.js
└── test
    ├── bird-test.js
    └── calc-test.js
3
5
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
3
5