The BDD style is exposed through expect
or should
interfaces. In both
scenarios, you chain together natural language assertions.
var expect = require('chai').expect;
expect(foo).to.equal('bar');
var should = require('chai').should();
foo.should.equal('bar');
Differences
The expect
interface provides a function as a starting point for chaining
your language assertions. It works on node.js and in all browsers.
The should
interface extends Object.prototype
to provide a single getter as
the starting point for your language assertions. It works on node.js and in
all browsers except Internet Explorer.
Configuration
By default, Chai does not show stack traces upon an AssertionError. This can
be changed by modifying the includeStack
parameter for chai.Assertion. For example:
var chai = require('chai');
chai.Assertion.includeStack = true;
Should Extras
Lorem ipsum
Language Guide
.keys(key1, [key2], [...])
Assert exact keys or the inclusing of keys using the contain
modifier.
expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);
expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');
.throw(constructor)
Assert that a function will throw a specific type of error, or specific type of error
(as determined using instanceof
), optionally with a RegExp or string inclusion test
for the error's message.
var err = new ReferenceError('This is a bad function.');
var fn = function () { throw err; }
expect(fn).to.throw(ReferenceError);
expect(fn).to.throw(Error);
expect(fn).to.throw(/bad function/);
expect(fn).to.not.throw('good function');
expect(fn).to.throw(ReferenceError, /bad function/);
expect(fn).to.throw(err);
expect(fn).to.not.throw(new RangeError('Out of range.'));
Please note that when a throw expectation is negated, it will check each
parameter independently, starting with error constructor type. The appropriate way
to check for the existence of a type of error but for a message that does not match
is to use and
.
expect(fn).to.throw(ReferenceError).and.not.throw(/good function/);
.closeTo(expected, delta)
Assert that actual is equal to +/- delta.
expect(1.5).to.be.closeTo(1, 0.5);