visit
If you want to write tests for your Nodejs app, you're spoilt for choice. You just run npm install
for the pleasure.
But unless we're doing some compilation for the front end or we're working with Typescript, why aren't we using NodeJS's native test runner? It's been around since version 18! That's April 2022. Almost two years in!
And straight from the .
// > node test.mjs
import test from 'node:test';
import assert from 'node:assert';
test('synchronous passing test', (t) => {
assert.strictEqual(1, 1);
});
✔ synchronous passing test (0.618667ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4.6255
We can even run tests spanning multiple files. As long as the file ends with an acceptable glob pattern, like *.test.mjs
, you can run the following:
node --test
Default globs are:
**/*.test.?(c|m)js
**/*-test.?(c|m)js
**/*_test.?(c|m)js
**/test-*.?(c|m)js
**/test.?(c|m)js
**/test/**/*.?(c|m)js
We even have watch mode, for goodness' sake. How did I not know about this?
node --test --watch
# node --test --experimental-test-coverage
ℹ tests 6
ℹ suites 2
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 54.586833
ℹ start of coverage report
ℹ --------------------------------------------------------------
ℹ file | line % | branch % | funcs % | uncovered lines
ℹ --------------------------------------------------------------
ℹ test.mjs | 100.00 | 100.00 | 100.00 |
ℹ test.test.mjs | 100.00 | 100.00 | 100.00 |
ℹ --------------------------------------------------------------
ℹ all files | 100.00 | 100.00 | 100.00 |
ℹ --------------------------------------------------------------
ℹ end of coverage report
describe/it
blocks? Yes, too! 🤯
describe('A thing', () => {
it('should work', () => {
assert.strictEqual(1, 1);
});
it('should be ok', () => {
assert.strictEqual(2, 2);
});
describe('a nested thing', () => {
it('should work', () => {
assert.strictEqual(3, 3);
});
});
});
▶ A thing
✔ should work (0.082667ms)
✔ should be ok (0.051292ms)
▶ a nested thing
✔ should work (0.05575ms)
▶ a nested thing (0.126541ms)
▶ A thing (0.512584ms)
Yet, proved you can have a sane zero-dependency mini without even a package.json
written in NodeJS:
"There's a place for complex frameworks and architectures, sure. But for many projects, they may be an overkill."
So if we're developing a project that's 1) small, 2) not really going to change much, and 3) only needs NodeJS, why not avoid using any dependencies at all and go native with node --test
?
Also published .