Chai Chai este o bibliotecă de aserțiuni BDD / TDD pentru Node.js și browser, compatibilă cu framework-uri de testare precum Mocha sau Jest.
Stilul BDD (expect)
const { expect } = require('chai');
Egalitate și tipuri
expect(val).to.equal(expected); // Egalitate strictă (===)
expect(val).to.eql(expected); // Egalitate profundă
expect(val).to.deep.equal(expected); // Identic cu .eql
expect(val).to.be.a('string');
expect(val).to.be.an('array');
expect(val).to.be.an.instanceOf(User);
Valori de adevăr și existență
expect(val).to.be.ok; // Valoare truthy
expect(val).to.be.true;
expect(val).to.be.false;
expect(val).to.exist; // Nu este null și nu este undefined
expect(val).to.be.null;
expect(val).to.be.undefined;
expect(val).to.be.empty; // Array, șir sau obiect gol
Comparații numerice
expect(score).to.be.above(5); // Mai mare decât (gt)
expect(score).to.be.at.least(5); // Mai mare sau egal cu (gte)
expect(score).to.be.below(10); // Mai mic decât (lt)
expect(score).to.be.at.most(10); // Mai mic sau egal cu (lte)
expect(score).to.be.within(5, 10); // Interval inclusiv
expect(pi).to.be.closeTo(3.14, 0.01); // Toleranță pentru numere zecimale
Obiecte și colecții
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');
Excepții aruncate de funcții
expect(() => badFunction()).to.throw();
expect(() => badFunction()).to.throw(TypeError);
expect(() => badFunction()).to.throw(/invalid argument/);
expect(() => goodFunction()).to.not.throw();
Stilul 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/);
Chai cu jQuery (chai-jquery)
chai.use(require('chai-jquery'));
// Verificări de stare 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 și atribute
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');