fabrizi0 fabrizi0 - 1 year ago 141
Javascript Question

Node.js assert library vs. other assert libraries

According to node.js assert library documentation:

The module is intended for internal use by Node.js, but can be used in
application code via require('assert'). However, assert is not a
testing framework, and is not intended to be used as a general purpose
assertion library.

I was looking at Chai as an alternative assert library (no BDD API, only the assert API), and at the end I see that the assert functionality is very similar.

Why Chai's assert library is a better assert library? It does everything than node.js does (beside being just more rich in terms of assertion available, but that's just syntactic sugar-coating). Even simple things like the total count of assert executed is not available on both.

Am I missing something ?

Answer Source

Here's the answer I posted to a very similar question on the Node.js issue tracker.

https://github.com/nodejs/node/issues/4532 and other issues allude to the reason the documentation recommends against using assert for unit testing: There are edge case bugs (or at least certainly surprises) and missing features.

A little more context: Knowing what we now know, if we were designing/building Node.js core all over again, the assert module would either not exist in Node.js or else consist of far fewer functions--quite possibly just assert() (which is currently an alias for assert.ok()).

The reasons for this, at least from my perspective, are:

  • all the stuff being done in assert could easily be done in userland
  • core efforts are better spent elsewhere than perfecting a unit testing module that can be done in userland

There's additional context that others may choose to add here or not (such as why, all things being equal, we would favor keeping core small and doing things in userland). But that's the so-called 30,000 foot view.

Since assert has been in Node.js for a long time and a lot of the ecosystem depends on it, we are unlikely (at least as best as I can tell at the current time) to ever remove assert.throws() and friends. It would break too much stuff. But we can discourage people from using assert and encourage them to use userland modules that are maintained by people who care deeply about them and who aggressively fix edge-case bugs and who add cool new features when it makes sense. So that's what that's all about.

True, if you're doing straightforward assertions with simple cases, assert probably will meet your needs. But if you ever outgrow assert, you'll be better off with chai or whatever. So we encourage people to start there. It's better for them (usually) and better for us (usually).

I hope this is helpful and answers your question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download