Skip to content

Instantly share code, notes, and snippets.

@makotot
Created November 1, 2012 16:30
Show Gist options
  • Select an option

  • Save makotot/3994857 to your computer and use it in GitHub Desktop.

Select an option

Save makotot/3994857 to your computer and use it in GitHub Desktop.
expect.jsのREADME.md

Expect.js

should.jsをベースに開発されたBDDアサーションライブラリ。

特徴

  • IE6+, Firefox, Chrome, Safari, Operaで動く

  • 全てのテストフレームワークで使用可能

  • NodeでもOK

  • スタンドアローン

使用方法

Node
$ npm install -g expect.js

でインストールして、対象ファイルで

var expect = require('expect.js');
ブラウザ
<script src="expect.js"></script>

API

ok : 値がtruthyか否か
expect(1).to.be.ok();
expect(true).to.be.ok();
expect({}).to.be.ok();
expect(0).to.not.be.ok();
be/equal : 厳密に等価な値か
expect(1).to.be(1)
expect(NaN).not.to.equal(NaN);
expect(1).not.to.be(true)
expect('1').to.not.be(1);
eql : 等価演算子で等価な値か(objectも含む)
expect({ a: 'b' }).to.eql({ a: 'b' });
expect(1).to.eql('1');
a/an : typeof演算子で、指定したデータ型の値か(arrayにも対応。instanceof演算子もOK)
// typeof(arrayにも対応)
expect(5).to.be.a('number');
expect([]).to.be.an('array');  // arrayでもtrue
expect([]).to.be.an('object'); // typeofなのでこれもtrue

// コンストラクタ
expect(5).to.be.a(Number);
expect([]).to.be.an(Array);
expect(tobi).to.be.a(Ferret);
expect(person).to.be.a(Mammal);
match : 文字列が正規表現に一致するか
expect(program.version).to.match(/[0-9]+\.[0-9]+\.[0-9]+/);
contain : 値が文字列/配列の中に含まれているか
expect([1, 2]).to.contain(1);
expect('hello world').to.contain('world');
length : 配列の長さが一致するか
expect([]).to.have.length(0);
expect([1,2,3]).to.have.length(3);
empty : 配列が空か否か
expect([]).to.be.empty();
expect({}).to.be.empty();
expect({ length: 0, duck: 'typing' }).to.be.empty();
expect({ my: 'object' }).to.not.be.empty();
expect([1,2,3]).to.not.be.empty();
property : プロパティとして存在するか
expect(window).to.have.property('expect')
expect(window).to.have.property('expect', expect)
expect({a: 'b'}).to.have.property('a');
key/keys : オブジェクトのkeyが存在するか
expect({ a: 'b' }).to.have.key('a');
expect({ a: 'b', c: 'd' }).to.only.have.keys('a', 'c');
expect({ a: 'b', c: 'd' }).to.only.have.keys(['a', 'c']);
expect({ a: 'b', c: 'd' }).to.not.only.have.key('a');
throwException/throwError : 対象の関数が例外処理を投げるか否か
expect(fn).to.throwError(); // 例外処理と同義
expect(fn).to.throwException(function (e) { // 例外オブジェクトを引数でとる
  expect(e).to.be.a(SyntaxError);
});
expect(fn).to.throwException(/matches the exception message/);
expect(fn2).to.not.throwException();
within : 数値が範囲内か
expect(1).to.be.within(0, Infinity);
greaterThan/above : より大きい値か
expect(3).to.be.above(0);
expect(5).to.be.greaterThan(3);
lessThan/below : より小さい値か
expect(0).to.be.below(3);
expect(1).to.be.lessThan(3);
fail : 強制的に失敗させる
expect().fail()
expect().fail("Custom failure message")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment