Chai Chai ist eine BDD / TDD-Assertion-Bibliothek für Node.js und den Browser, die nahtlos mit JavaScript-Test-Frameworks wie Mocha oder Jest harmoniert.
BDD-Stil (expect)
const { expect } = require('chai');
Gleichheit & Typen
expect(val).to.equal(expected); // Strikte Gleichheit (===)
expect(val).to.eql(expected); // Tiefe Gleichheit
expect(val).to.deep.equal(expected); // Identisch mit .eql
expect(val).to.be.a('string');
expect(val).to.be.an('array');
expect(val).to.be.an.instanceOf(User);
Wahrheitswerte & Vorhandensein
expect(val).to.be.ok; // Truthy-Wert
expect(val).to.be.true;
expect(val).to.be.false;
expect(val).to.exist; // Weder null noch undefined
expect(val).to.be.null;
expect(val).to.be.undefined;
expect(val).to.be.empty; // Array, String oder Objekt mit Länge bzw. Schlüsseln gleich 0
Numerische Vergleiche
expect(score).to.be.above(5); // Größer als (gt)
expect(score).to.be.at.least(5); // Größer oder gleich (gte)
expect(score).to.be.below(10); // Kleiner als (lt)
expect(score).to.be.at.most(10); // Kleiner oder gleich (lte)
expect(score).to.be.within(5, 10); // Inklusiver Wertebereich
expect(pi).to.be.closeTo(3.14, 0.01); // Gleitkomma-Toleranz
Objekte & Collections
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');
Funktionsfehler & Exceptions
expect(() => badFunction()).to.throw();
expect(() => badFunction()).to.throw(TypeError);
expect(() => badFunction()).to.throw(/invalid argument/);
expect(() => goodFunction()).to.not.throw();
TDD-Stil (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 mit jQuery (chai-jquery)
chai.use(require('chai-jquery'));
// DOM-Zustandsprüfungen
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 & Attribute
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');