In No API Is the Best API — The elegant power of Power Assert, we take a look at how Power Assert can be used to automatically generate contextual error messages when using Node's assert module for assertions. This allows you to get the best of both worlds; you can use a very simple assertion API while still taking advantage of rich and useful assertion messages. Power Assert accomplishes this by transforming your tests before they run and using the code itself to determine the relevant information to display. You can check out the original article for more details, but here we'll just focus on the project configuration and running the tests.
The project dependencies are listed in package.json and yarn.lock. You can install them by running the following.
# Or: `npm install`
yarn install
This will install the Mocha test runner, a few Babel-related packages, Power Assert, and the Power Assert Babel Preset inside of node_modules/
.
The key to the tests being transformed when the tests are run is the Babel configuration.
It's located in .babelrc, and it tells Babel to use the Power Assert preset when NODE_ENV
is set to testing
.
It also specifies that the Babel env preset should be used to target Node v6.10.
The non-testing Babel configuration can be customized freely without impacting the use of Power Assert.
It's also worth mentioning that Mocha needs to be configured to use Babel in order for the tests to be transformed.
This is accomplished using Babel register and the Mocha --require
option.
NODE_ENV=testing mocha --exit --require babel-register"
This same command is included in package.json as a script, so it's equivalent to running yarn test
.
The tests themselves are all located in test/test-assertion-errors.js.
There's nothing specific to Power-Assert in the tests, they're just generic tests that use Node's assert
module.
They are each purposely designed to fail however, so that you can easily see what the error messages generated by Power Assert look like.