I believe this straightforward illustration effectively clarifies their distinctions
Assert
var assert = require('chai').assert
const foo = 'bar'
const beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
assert.typeOf(foo, 'string'); // without optional message
assert.typeOf(foo, 'string', 'foo is a string'); // with optional message
assert.equal(foo, 'bar', 'foo equal `bar`');
assert.lengthOf(foo, 3, 'foo`s value has a length of 3');
assert.lengthOf(beverages.tea, 3, 'beverages has 3 types of tea');
For all scenarios, the assert style allows you to add an optional message as the final parameter in the assert statement. These messages will be displayed in error messages if your assertion fails.
Note
expect
and should
use chainable language for creating assertions, but they differ in how an assertion is first established. With should
, there are also some limitations and additional tools available to address these shortcomings.
Expect
var expect = require('chai').expect
const foo = 'bar'
const beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);
expect(beverages).to.have.property('tea').with.lengthOf(3);
expect
enables you to include customized messages before any failed assertions occur.
var answer = 43;
// AssertionError: expected 43 to equal 42.
expect(answer).to.equal(42);
// AssertionError: topic [answer]: expected 43 to equal 42.
expect(answer, 'topic [answer]').to.equal(42);
This feature is useful when dealing with vague topics such as booleans or numbers.
Should
The should
style offers the same chainable assertions as the expect interface, but it augments each object with a should property to initiate the chain. However, this method may encounter compatibility issues when used in Internet Explorer.
var should = require('chai').should() //actually call the function
const foo = 'bar'
const beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };
foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.lengthOf(3);
beverages.should.have.property('tea').with.lengthOf(3);
Differences between expect and should
Initially, notice that the expect
require simply references the expect
function, while with the should
require, the function is executed.
var chai = require('chai')
const expect = chai.expect
const should = chai.should();
The expect interface provides a function to start chaining your language assertions. It functions on node.js and all browsers.
The should interface enhances Object.prototype to offer a single getter as the starting point for your language assertions. It works on node.js and all modern browsers except Internet Explorer.