12
8

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.

クライアントサイドjavascriptの単体テスト

Last updated at Posted at 2016-04-07

テストしにくいことに定評のあるjavascriptさん
特にDOM操作が入ったりするとテストするのが非常に厄介

今回はmochaを使ってそんなjavascriptさんの単体テストをどうにか実現したお話です

ディレクトリ構成

とりあえずサンプルなのでこんな感じで
sample.test.htmlがテストを実行するファイルです。

project_root/
├-node_modules
├-public
|  └-js
|     └sample.js
├-tests
|  └sample.test.html
└-package.json

テスト対象

今回は簡単な例として下記のようなソースをテストするとします
入力された値が奇数ならtrue、偶数ならfalseを返す簡単な関数です

sample.js
function isOdd(inputNum){
    return inputNum % 2 === 1;
}

パッケージインストール

最低限必要なのはテストフレームワークのmocha
あとpower-assertもテスト失敗時に得られる情報が多くなるので入れておく
テスト用なのでdevDependenciesに保存

npm install mocha power-assert --save-dev

テストコード作成

sample.test.html
<!DOCTYPE html>
<html>
<head>
    <title>sample test</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../../node_modules/mocha/mocha.css" />
    <!--テストフレームワーク-->
    <script src="../../node_modules/mocha/mocha.js"></script>
    <script src="../../node_modules/power-assert/build/power-assert.js"></script>
    <!--テスト対象のスクリプト-->
    <script src='../public/js/sample.js'></script>
</head>
<body>
<!-- ここにテスト結果が表示される -->
<div id="mocha">
</div>
<script>
    // setup mocha
    mocha.setup('bdd');
    mocha.reporter('html');
    
    describe("sample test", function(){
        it("should return true", function(){
            assert(isOdd(7) === true);
        });
        it("should return false", function(){
            assert(isOdd(6) === false);
        });

    });
    // run test
    mocha.run();
</script>
</body>
</html>

scriptタグのsrc属性を全て相対パスで書いているのは、直接htmlファイルを開くだけでもテスト結果がわかるようにです。

テスト結果はこんな感じ
スクリーンショット 2016-04-07 21.29.55.png

今回は使ってませんが、jQueryを使ったDOM操作とかもhtmlに必要な要素を足せばできます。

このは今回作ったテストを自動で実行するようにします

12
8
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
12
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?