Use Node built-ins to test small projects
In short: small Node projects don’t need a testing framework like Jest or Mocha. You can just use Node’s built-in assert
module and a test script.
I maintain a few npm packages. Some of them are very small—often just a single short function. For example, I maintain percentage
, a tiny package that formats numbers like 0.12
as 12%
.
I write tests for these packages, of course. I used to use a testing framework, such as Mocha or Jest. But for my smaller packages, I’ve stopped doing that.
I’ve dropped these dependencies and put everything into a single test file, which I run with node test.js
. For example, here are the abbreviated tests for percentage
:
import percentage from "./percentage.js";
import assert from "assert";
assert.strictEqual(percentage(0.12), "12%");
assert.strictEqual(percentage(1), "100%");
// ...
(The above code is simplified. You can see the full tests in the repository.)
You lose some fancy test output and test organization, but you gain simplicity and fewer dependencies.
I also update the test
script in package.json
, so npm test
works just fine. It just looks like this:
...
"scripts": {
...
"test": "node test"
},
...
This doesn’t work for larger projects, but for small ones, it’s a pattern I like.