Assertion
Node.js has built-in assertion module.
// add assertion module
const assert = require('assert');
...
// using
assert(true); // ok
assert(1); // ok
assert(typeof 123 === 'string'); // fail
Below list of most useful methods.
method | description |
---|---|
ok(v [, msg]) | Tests if v is truthy. It is equivalent to assert.equal(!!value, true, message). It is alias for call function operator, i.e. assert.ok(v) same as assert(v). |
strictEqual(v, expd [, msg]) | Tests strict equality between the v and expd parameters. |
notStrictEqual(v, expd [, msg]) | Tests strict equality between the v and expd parameters. |
deepStrictEqual( |
Tests for deep equality between the v and expd parameters. "Deep" equality means that the enumerable "own" properties of child objects are recursively evaluated also by the following rules. |
notDeepStrictEqual( |
Tests for deep equality between the v and expd parameters. |
fail(msg) | Throws an AssertionError with the provided error message or a default error message. If the message parameter is an instance of an Error then it will be thrown instead of the AssertionError. |
ifError(v) | Throws v if v is not undefined or null. This is useful when testing the error argument in callbacks. |
Chai framework
Chai is available for both node.js and the browser using any test framework you like. There are also a number of other tools that include Chai.
# install chai on Node.js
npm install chai
Recommend adding it to package.json devDependencies using a * as the version tag.
"devDependencies": {
"chai": "*",
"mocha": "*"
},
Chai supports several assertion interfaces. "Assert" style extends api of built-in Node.js assert module.
// add chai framework
var assert = require('chai').assert;
...
// using
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 using in browser you need add chai script file, which define global object chai.
<script src="chai.js" type="text/javascript"></script>
...
<script>
describe('test suite', function() {
it('some tst', function() {
chai.assert(true);
});
});
...
</script>
See more about Chai framework on official site.