6.4 Using an Assertion Libarary

We have been repeating

if (res != 44)
throw new Error(`Expected 44, but got ${res}.`);

and

it('should sqare two numbers', ()=> {
var res = utils.square(50);
if (res != 2500)
throw new Error(`Expected 250, but got ${res}.`);
});

Use expect library
npm install expect@1.20.2 --save-dev

const expect = require('expect');
const utils = require('./utils');
it('should add two numbers', ()=> {
var res = utils.add(33, 11);
expect(res).toBe(44);
// if (res != 44)
// throw new Error(`Expected 44, but got ${res}.`);
});
it('should sqare two numbers', ()=> {
var res = utils.square(50);
expect(res).toBe(2500);
// if (res != 2500)
// throw new Error(`Expected 250, but got ${res}.`);
});

Chain multiple assertions:
expect(res).toBe(44).toBeA('number');


Other expects

There are working good for most types but not for Arrays or Objects.

expect({name: 'Jude'}).toBe({name: 'Jude'}); will not pass.

To solve this problem, use

expect({name: 'Jude'}).toEqual({name: 'Jude'}); will not pass.


.toInclude for Array
expect([2, 3, 4]).toInclude(3);
Similar to .toExclude

These are compatible with Objects as well.

Example:
expect({name: 'Jude', age: 10}).toInclude({age: 10}) will pass.