Chai Chai は、Node.js およびブラウザ環境に対応し、Mocha や Jest などの各種テストフレームワークと併用可能な BDD / TDD アサーションライブラリです。
BDD スタイル (expect)
const { expect } = require('chai');
値の等価性と型チェック
expect(val).to.equal(expected); // 厳密等価比較 (===)
expect(val).to.eql(expected); // ディープ等価比較 (オブジェクト・配列の再帰的検証)
expect(val).to.deep.equal(expected); // .eql と同等のディープ比較
expect(val).to.be.a('string');
expect(val).to.be.an('array');
expect(val).to.be.an.instanceOf(User);
真偽値・存在チェック
expect(val).to.be.ok; // 真値 (Truthy) であることを検証
expect(val).to.be.true;
expect(val).to.be.false;
expect(val).to.exist; // null または undefined でないことを検証
expect(val).to.be.null;
expect(val).to.be.undefined;
expect(val).to.be.empty; // 配列・文字列・オブジェクトが空(要素数 0)
数値の大小比較
expect(score).to.be.above(5); // より大きい (gt)
expect(score).to.be.at.least(5); // 以上 (gte)
expect(score).to.be.below(10); // より小さい (lt)
expect(score).to.be.at.most(10); // 以下 (lte)
expect(score).to.be.within(5, 10); // 指定範囲内(両端を含む)
expect(pi).to.be.closeTo(3.14, 0.01); // 浮動小数点の許容誤差比較
オブジェクトとコレクションの検証
expect(array).to.include(item);
expect(array).to.have.members([1, 2, 3]);
expect(array).to.have.lengthOf(3);
expect(obj).to.have.property('name');
expect(obj).to.have.property('name', 'Alice');
expect(obj).to.have.nested.property('address.city', 'London');
expect(obj).to.have.all.keys('id', 'name');
関数の例外スロー検証
expect(() => badFunction()).to.throw();
expect(() => badFunction()).to.throw(TypeError);
expect(() => badFunction()).to.throw(/invalid argument/);
expect(() => goodFunction()).to.not.throw();
TDD スタイル (assert)
const { assert } = require('chai');
assert.ok(val, 'value is truthy');
assert.equal(actual, expected, 'compares with ==');
assert.strictEqual(actual, expected, 'compares with ===');
assert.deepEqual(actual, expected, 'deep equality');
assert.isTrue(val);
assert.isFalse(val);
assert.isNull(val);
assert.isNotNull(val);
assert.isUndefined(val);
assert.isDefined(val);
assert.typeOf(val, 'string');
assert.instanceOf(val, Model);
assert.lengthOf(val, 3);
assert.include(list, item);
assert.match(str, /regex/);
assert.throws(() => { /* error test */ }, /error regex/);
jQuery との連携 (chai-jquery)
chai.use(require('chai-jquery'));
// DOM 要素の表示・有効状態チェック
expect($elem).to.be.visible;
expect($elem).to.be.hidden;
expect($elem).to.be.enabled;
expect($elem).to.be.disabled;
expect($elem).to.be.checked;
// CSS クラスと属性の検証
expect($elem).to.have.class('active');
expect($elem).to.have.id('submit-btn');
expect($elem).to.have.attr('disabled');
expect($elem).to.have.css('display', 'block');
expect($elem).to.have.text('Hello World');