k01ken’s b10g

He110 W0r1d!

Mochaを使ってJavaScriptのテストコードを書いて検証してみる

開発環境は、Windows 10 Pro(64bit)。

node.jsを事前にインストールしていることが前提条件です。

Mocha
Mocha - the fun, simple, flexible JavaScript test framework

1.テスト用のディレクトリを作成するため、コマンドプロンプト上で以下のコマンドを入力。

cd c:\ && mkdir mocha_test && cd mocha_test

2. 以下のコマンドを入力して、package.jsonを作成する。質問に対してはすべてEnterキーで返す。

npm init

3.以下のコマンドを入力して、Mochaをインストールする

npm install -D mocha

続いて、以下のコマンドを入力して、shouldをインストールします

npm install -D should

4.テストコードを入れるためにtestディレクトリを作成する

mkdir test

5.テストするためのコードを書いて、index.jsとして保存します。

var index = {
  addition : function(a,b){
    return a+b;
  }
};

module.exports = index;

6.テストコードを書いて、testディレクトリ内に、index.test.jsとして保存します。

var should  = require('should');
var index = require('../index.js');

describe('index', function(){
  it('3+4=7', function(){
    index.addition(3,4).should.equal(7);
  });
});

7.package.jsonのscriptsのtestの値をmochaに変更します。

  "scripts": {
    "test": "mocha"
  },

8.以下のコマンドを入力して、テストを実行します。

npm test

テスト結果
f:id:k01ken:20200110223858p:plain
テストがうまく通りました。


参考リンク
gulpで自動テストとコード圧縮 - Qiita