Source code is a communication tool. It tells other developers what the machine will do to the input data. Sometimes the source code gets executed by an actual computer. The execution is fast, but human reading and understanding is slow. At some threshold, the communication breaks down and a bug is introduced because someone did not understand what the code meant to say.
There are syntax features that source code can use to express itself better. Naming functions and variables for example is a primary syntax feature used to make code's purpose clear:
1 | // avoid this |
Staticly typed languages (C, C++, Java) use type syntax to add meaning to the source code
int function add(int a, int b) { return a + b; }
JavaScript does not have type declarations, but the language's flexibility makes creating an assertion library to check types very easy. There are lots of different libraries that verify different properties. Using one or several libraries and sprinkling assertions throughout the code makes its meaning clear. Here are several libraries. Main comparison criteria:
- expressiveness - how many different assertions are there?
- pulse - is the project being actively maintained?
- extensibility - can we add our own assertions?
- ease of use - is it hard to start using it?
check-types
check-types by Phil Booth has two modes: checking and verifying. Any check method returns true or false. Any verify method throws an exception if a condition is false
1 | check.verify.unemptyString('label-1', 'missing a label'); |
check-types supports checking complex objects and iterating over a collection.
1 | check.verify.like({}, { foo: 'bar' }, 'Invalid object'); |
Can be extended by attaching methods directly to check
object.
check-types shortcomings
- Only a single message argument after predicate,
thus requires building a string
check.number(foo, 'foo should be a number, is ' + foo);
- No throwing exception support - only really needed in the unit test code, not in production code.
expect.js
expect.js is single Jasmine-style expect(value)...
function with chained assertions
1 | expect(5).to.be.a('number'); |
Supports running functions and checking exceptions
1 | expect(fn).to.throwException(function (e) { // get the exception object |
In general I use this library when unit testing using mocha. The syntax is very descriptive.
expect.js shortcomings
- Has not been maintained in 2 years, lots of open issues and pull requests. There are lots of forks though.
- No collection support or nested properties tests.
- Lacks any additional information in the exception, seems geared towards the unit testing.
- Conflicts with Jasmine's
expect
function
should.js
should.js is by express/jade/mocha's author
TJ Holowaychuk so it has been extensively field-tested and
very battle-hardened. Nice syntax and lots of built-in assertions. It extends Object.prototype
with single non-enumerable property .should
with chained assertions
1 | var user = { |
In some cases, a variable is not an Object (for example a primitive), so you need to use a static function to perform assertion
1 | should(true).ok; |
Optional error message can be passed into several assertions: eql, equal, within, instanceof, above, below, match, length, property, ownProperty.
Failed assertion generally has sensible information, for example
1 | ({foo: 'bar'}).should.have.property('zzz'); |
should.js shortcomings
- Unclear how to add custom assertions, but the built-in coverage is great.
- Uses expressions like
foo.should.be.an.Array
, breaking jshint and eslint (no unused expressions) - Breaks closure JavaScript minifier, mostly due to lots of expressions.
Jasmine matchers
I thought about using Jasmine with its collection of matchers in the production code, since we already use it in unit testing. Ultimately I rejected this approach, since this brings the entire Jasmine runtime.
contractual
Contractual exploits JavaScript label syntax quirk to check pre- and post- conditions. Because results of the expressions do not have to be used, you can write the following:
1 | function divide (a, b) { |
If you run the above code, the preconditions will execute, but they will not affect the result, even if they fail. Contractual comes with a compiler that can transpile the above code into source code with actual assertions:
1 | var OBLIGATIONS = require('obligations'); |
contractual shortcomings
- Extra compiling step.
- Generates 'precondition failed' message.
- Cryptic error message if postcondition failed.
It seems this interesting library is too immature to use in production.
Other thoughts
It seems a good assertion library is hard to pick. My favorites are check-types and expect.js. Because the expect.js project is not actively maintained I would use should.js instead. Still, after considering all aspects, I pick check-types.
- Easy to read, natural syntax
check.verify.number(foo, 'foo should be ...')
- Good api coverage, works on Node and in browser.
- Assertions that can check collections, including recursive property checks
- Does not break minification tools
- Does not cause JSHint warnings
- Easy to extend with new methods
check.verify.foo = function (val, message) { ... }
- Small.
Update 1
In the end we wrote our own library of lazy assertions - pass as many arguments as needed without paying performance penalty, because the exception message will be formed only if the first argument is falsy. See lazy-ass on github.