LoginSignup
21
21

More than 5 years have passed since last update.

Node.jsでmochaを使ってBDDスタイルのユニットテスト

Posted at

mocha

mocha(モカ)と読む。Javascriptの単体テストフレームワーク。

mochaの特徴

  • node.jsやブラウザから実行可能できる。
  • 非同期のテストもできる。
  • TDDやBDDスタイルでテストを記述できる。
  • テスト結果も多くの形式で出力できる。
  • mocha自体はアサーション機能を持たない。
    → 値の検証には標準のassertやchai、shouldを使用する。

mochaをインストール

mochaをグローバルインストールする。

$ npm install -g mocha

chai

chaiはBDD / TDDスタイルで記述できるアサーションライブラリ。
BDDスタイルは、expect / shouldが用意されており、TDDスタイルはassertで表現する。

shouldとexpectの違い

sholudはObject自身を拡張して、sholudメソッドを追加して実装されている。
英語の文法に近い記述ができる。
メモ:どうもIEとはは相性がよろしくないみたい。

shouldの例
// 「fooがbarと等しくなければいけない」ことをテスト。
foo.should.equal('bar');

expectは関数で、引数に評価する値を渡す。

expectの例
expect(foo).to.equal('bar'); 

chaiをインストール

$ npm install chai

chai自体はTDDとBDDに対応していが、まずは、BDDスタイルのshouldでテストを作ってみた。

実装とテスト

プロジェクトの作成

sample-mocha
├── src
│   └── calculation.coffee
└── test
    └── calculation-bdd-should.coffee

テスト対象の作成

calculation.coffee
class Calculator

  constructor: () ->
    console.log 'Calcクラスのインスタンスを生成する。'

  add: (a, b) ->
    ans = a + b
    return ans

  multiply: (a, b) ->
    ans = a* b
    return ans

module.exports = Calculator

テストコードを書いてみる

mochaではBDD向けのスタイルとして以下が提供されている。

関数 概要
describe ネスト管理可能な階層。テスト対象を宣言する。
before describeの前に実行される。前提条件を記述する。
after describeの後に実行される。後処理を記述する。
beforeEach 各describeの前に実行される。前提条件を記述する。
afterEach 各describeの後に実行される。後処理を記述する。
it 検証内容を記述する。
calculation-bdd-should.coffee
should = require('chai').should();

Calculator = require '../src/calculator'

# テスト対象を宣言
describe 'Calculator', () ->

  calc = null

  # 各describeの前
  before () ->
    console.log 'before method'
    calc = new Calculator()

  # 各describeの後
  after () ->
    console.log 'after method'
    calc = null

  # 各itの前
  beforeEach () ->
    console.log 'beforeEach method'

  afterEach () ->
    console.log 'afterEach method'

  # 実行するテストコード
  it '1 + 2 = 3', () ->
    calc.add(1, 2).should.equal(3)
  it '1 * 2 = 2', () ->
    calc.multiply(1, 2).should.equal(2)

テストの実行

$ mocha --compilers coffee:coffee-script/register test/

  Calculator
before method
Calcクラスのインスタンスを生成する。
beforeEach method
    ✓ 1 + 2 = 3
afterEach method
beforeEach method
    ✓ 1 * 2 = 2
afterEach method
after method


  2 passing (7ms)
21
21
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
21
21