Assertions provided by node.js assert for unit-testing are very limited. Even before I've written the first test I was already creating a few of assertions as it was clear I will keep re-using them.
Could you recommend some good library of assertions to test for common javascript situations (object structures, objects classes, etc., etc.)?
Ideally it should integrate well with nodeunit (or, better, extend it's assertions) - my assertions do not, I have to pass them test
as an extra variable...
The only one I've seen is Chai. What could you say about it?
For Node 10 and above, it's better to use strict assert which can be imported as named import and renamed for convenience as assert : import { strict as assert } from 'assert'; assert. ok(true); assert(true);
In test codes, assert module's assert. equal are heavily used. It is legacy API and deprecated since Node. js v9.
Assertion libraries are tools to verify that things are correct. This makes it a lot easier to test your code, so you don't have to do thousands of if statements. Example (using should.js and Node.js assert module): var output = mycode.
If you've ever written tests for a Node. js application, chances are you used an external library. However, you don't need a library to run unit tests in Javascript.
It's also somewhat a matter of preference — whether you prefer to test with the assert
syntax or BDD-style assertions (smth.must.equal(...)
).
For the assert style, Chai's assert may work well. It has more built-in matchers that Node's own assert module.
If you find the BDD-style more readable and fluent, all three do that:
They differ primarily by the simplicity or complexity of their API when it comes to various matchers. Their essential equality assertions, though, are interchangable — foo.must.equal(42)
or foo.should.equal(42)
.
There's one thing you need to be aware when picking Chai.js and Should.js that I argue is a fundamental design mistake — their practice of asserting on property access as opposed to calling the matcher as a function. I've written a critique of asserting on property access and how it may cause false positives in tests.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With