LoginSignup
81
79

More than 5 years have passed since last update.

【npm + Karma + Jasmine】JavaScriptの単体テスト環境を構築する

Last updated at Posted at 2014-08-07

JavaScriptの単体テスト環境構築のまとめ。
テストランナーとして「Karma」、テストフレームワーク・アサーションライブラリとして「Jasmine」を使う。

前提条件

下記が使用できること。

  • node
  • npm

検証環境

  • MacOS X 10.9.2

package.json生成

$ npm init
  • 対話形式でprojectの初期設定をする。
  • 不要な項目は、空欄のままEnter
  • 最終的に、package.jsonファイルが生成される(直接編集も可)

console12.png

karmaインストール

$ npm install --save-dev karma
  • node_modules/が生成され、その中に karma 関連ファイルが格納される
  • option「–save-dev」によって、install 対象の library 情報が自動で package.json に記述される
package.json
{
  "name": "JSTestSample",
  "version": "0.0.0",
  "description": "Sample for JS Test.",
  "main": "index.js",
  "scripts": {
    "test": "node_modules/karma/bin/karma start"
  },
  "author": "",
  "license": "not commedical",
  "devDependencies": {
    "karma": "~0.12.9"
  }
}

karma init

$ node_modules/karma/bin/karma init
  • 対話形式で情報を入力
  • karma.conf.jsが作成される
  • package.json に jasmine 関連ファイルと、chrome-lancher が記述される

f7b5a0c19662aca94a8b1185006aff11.png

package.json
"devDependencies": {
 "karma": "~0.12.9",
 "karma-jasmine": "~0.1.5",
 "karma-chrome-launcher": "~0.1.3"
 }

プロダクトコード+テストコード

Logic.js
function Logic() {

}

Logic.prototype.squaredNumber = function(num){
    return num * num;
};
LogicTest.js
describe("TestSample>", function(){
    describe("Logic>", function() {
        it("multiNumber", function() {
            var target = new Logic();
            var num = 3;
            var expected = 10;

            var result = target.squaredNumber(num);

            expect(expected).toEqual(result);

        })
    });
});

テスト実行コマンドを設定

package.json
{
  "name": "JSTestSample",
  "version": "0.0.0",
  "description": "Sample for JS Test.",
  "main": "index.js",
  "scripts": {
    "test": "node_modules/karma/bin/karma start"
  },
  "author": "",
  "license": "not commedical",
  "devDependencies": {
    "karma": "~0.12.9",
    "karma-jasmine": "~0.1.5",
    "karma-chrome-launcher": "~0.1.3"
  }
}

テスト実行してみる

$ npm test
  • package.json の情報を元にテストが実行される
  • chromeが自動で起動する

9543f2264fdc21a1e9324dedb508ef50.png

  • テスト成功時

92b6b0307cd4d648c7eb2c0d593333dc.png

  • テスト失敗したときはこんな感じ

92b6b0307cd4d648c7eb2c0d593333dc1.png

81
79
2

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
81
79