Testing Through assert
assert is a core library that provides the basis for testing code. Node’s
assertions works pretty much like the same feature in other languages and
environments: they allow you to make claims about objects and function
calls and send out messages when the assertions are violated. These
methods are really easy to get started with and provide a great way to
unit test your code’s features. Node’s own tests are written with assert.
Most assert
methods come in pairs: one method providing the positive test and the
other providing the negative one. For
instance, Example 5-37 shows equal() and notEqual(). The methods take two arguments: the first is the expected
value, and the second is the actual value.
Example 5-37. Basic assertions
> var assert = require('assert');
> assert.equal(1, true, 'Truthy');
> assert.notEqual(1, true, 'Truthy');
AssertionError: Truthy
at [object Context]:1:8
at Interface.<anonymous> (repl.js:171:22)
at Interface.emit (events.js:64:17)
at Interface._onLine (readline.js:153:10)
at Interface._line (readline.js:408:8)
at Interface._ttyWrite (readline.js:585:14)
at ReadStream.<anonymous> (readline.js:73:12)
at ReadStream.emit (events.js:81:20)
at ReadStream._emitKey (tty_posix.js:307:10)
at ReadStream.onData (tty_posix.js:70:12)
>The most obvious thing here is that when an
assert method doesn’t pass, it throws an exception. This is a fundamental principle in the test suites. When a test suite runs, it should just run, without throwing an exception. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access