LoginSignup
8
6

More than 5 years have passed since last update.

mocha + chai.should で null や undefined をテストする

Posted at

問題点

chai.shouldObject のプロトタイプに should というメソッドを追加することで実装されているので、 Object のプロトタイプを継承していない nullundefinedshould というメソッドを持たない。そのため、普段と同じ語順でテストしようとするとエラーになる。

null.should.be.null
undefined.should.be.undefined

# TypeError: 'null' is not an object (evaluating 'restDaysText(dest, src).sould')

解決策

chai.should() の戻り値のオブジェクトを使う方法1

公式に提供されている方法を使う。普段と語順は違うがチェックできる。

var should = chai.should();

// example が `null` か `undefined` であることをテストする。
should.not.exist(example);

// example が `null` であることをテストする。
should.equal(example, null);

// example が `undefined` であることをテストする。
should.equal(example, undefined);

CoffeeScript の存在演算子を使う方法

CoffeeScript の存在演算子を使うと、普段と同じ語順で短くテストを書くことができる。

# example が `null` か `undefined` であることをテストする。
example?.should.be.false

  1. How to assert null with should · Issue #90 · chaijs/chai よりコードを引用(コメント内意訳 + undefined のテストを追加) 

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