빠른 참조

Chai.js 단언 라이브러리 치트시트

Chai.js 퀵 레퍼런스: BDD expect 및 should 스타일, TDD assert 스타일, 깊은 동등성, 타입 검사 및 chai-jquery 단언문.

· 게시일

Chai Chai는 Node.js 및 브라우저 환경에서 Mocha, Jest 등 다양한 테스트 프레임워크와 결합하여 사용하는 BDD / TDD 단언(Assertion) 라이브러리입니다.

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;        // 배열, 문자열 또는 객체가 비어있음

수치 비교

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');

관련 주제