Karma + Jasmineによるユニットテスト

自作しているWeb Audio APIのライブラリ XSound.jsでKarma + Jasmineによるユニットテストを始めたので, その備忘録として記載しておきます.

Karma + Jasmineによるユニットテストの環境構築は前日の記事を参考にしてください.

1. Karma設定ファイルの生成

まず. テスト対象となるディレクトリで以下のコマンドを実行します.

$ karma init

コマンドを実行すると, 初期化ウィザードが出力されるので, 順に入力していきます.

1 – 1. テスティングフレームワークの選択

Which testing framework do you want to use ?
Press tab to list possible options. Enter to move to the next question.
> jasmine

1 – 2. RequireJSを利用するかどうか. 利用するのであれば, yesを入力

Do you want to use Require.js ?
This will add Require.js plugin.
Press tab to list possible options. Enter to move to the next question.
> no

1 – 3. テストを実行するブラウザを指定.

事前に対象ブラウザのランチャーをインストールしておきましょう.

Do you want to capture any browsers automatically ?
Press tab to list possible options. Enter empty string to move to the next question.
> Chrome
> 

1 – 4. テスト対象のディレクトリの指定

今回は, src以下にテスト対象のファイルを, test以下にテストコードを置くことにするので, 以下のように指定します.

What is the location of your source and test files ?
You can use glob patterns, eg. "js/*.js" or "test/**/*Spec.js".
Enter empty string to move to the next question.
> src/*.js
> test/*.js

> 

1 – 5. 指定したディレクトリ内でテスト対象から除外したいファイルを指定します.

Should any of the files included by the previous patterns be excluded ?
You can use glob patterns, eg. "**/*.swp".
Enter empty string to move to the next question.
> 

1 – 6. 対象ファイルが更新される度にテストを実行するかどうか.

Do you want Karma to watch all the files and run the tests on change ?
Press tab to list possible options.
> yes

以上を入力すると, 実行したディレクトリにkarma.conf.jsという設定ファイルが生成されます.

2. テスト対象のファイルの作成

今回は, toFrequencies関数をテスト対象とします. メソッド内容は以下のような感じです.

to-frequencies.js

/** 
 * This function calculates frequency from the index that corresponds to the 12 equal temperament.
 * @param {Array.} indexes This argument is array of index that corresponds to the 12 equal temperament.
 *     For example, This value is between 0 and 88 in the case of piano.
 * @return {Array.} This is returned as array of frequencies.
 */
var toFrequencies = function(indexes) {
    // The 12 equal temperament
    //
    // Min -> 27.5 Hz (A), Max -> 4186 Hz (C)
    //
    // A * 1.059463 -> A# (half up)

    var FREQUENCY_RATIO = Math.pow(2, (1 / 12));  // about 1.059463
    var MIN_A           = 27.5;

    if (!Array.isArray(indexes)) {
        indexes = [indexes];
    }

    var frequencies = new Array(indexes.length);

    for (var i = 0, len = indexes.length; i < len; i ++) {         var index = parseInt(indexes[i]);         frequencies[i] = (index >= 0) ? (MIN_A * Math.pow(FREQUENCY_RATIO, index)) : 0;
    }

    return frequencies;
};

テスト対象のコードなので, これをsrc以下に置きます.

3. テストコードファイルの作成

テストコードはJasmineの仕様にしたがって記述します.
describeでテストのグループ化をして, itで個々のテストを記述していきます.

また, expectの引数には実際の値を指定し, Matcherの引数 (コード例ではtoBe) には期待する値を指定します.

Macherには,toBeメソッド以外にもたくさんあるので, こちらを参考に必要に応じて使い分けてください.

test-to-frequencies.js

describe('toFrequencies()', function() {

        // Negative
        it('should return 0 or empty array', function() {
            expect(X.toFrequencies()[0]).toEqual(0);
            expect(X.toFrequencies(-1)[0]).toEqual(0);
            expect(X.toFrequencies([-1])[0]).toEqual(0);
            expect(X.toFrequencies([])).toEqual([]);
        });

        // Positive
        it('should return number', function() {
            expect(X.toFrequencies(0)[0]).toEqual(27.5);
            expect(Math.floor(X.toFrequencies(48)[0])).toEqual(440);
            expect(Math.floor(X.toFrequencies(87)[0])).toEqual(4186);
        });

        it('should return array that contains numbers', function() {
            var frequencies = X.toFrequencies([0, 48, 87]);

            frequencies.forEach(function(element, index) {
                if (index !== 0) {
                    frequencies[index] = Math.floor(element);
                }
            });

            expect(frequencies).toEqual([27.5, 440, 4186]);
        });

 });

テスト対象のコードなので, これをtest以下に置きます.

4. テストの実行

あとは, テストを実行するだけです. テストを実行するには以下のコマンドを実行します.

$ karma start

コマンドを実行すると, 設定ファイルで指定したブラウザが起動し, 以下のような画面が表示されます.

Karma テストの実行
Karma テストの実行

また, ターミナルにもテスト結果が表示されます.

INFO [karma]: Karma v0.12.31 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 40.0.2214 (Mac OS X 10.9.5)]: Connected on socket _RA_ZqrC2-TO8Bf0jMVB with id 88154411
Chrome 40.0.2214 (Mac OS X 10.9.5): Executed 4 of 4 SUCCESS (0.015 secs / 0.009 secs)

あとは, テストをパスするように, コードの修正を繰り返します.
設定ファイルで更新の度にテストするようにしておけば, 再度テスト実行のコマンドを入力する必要もありません.

コメントを残す