Codementor Events

Built-in Testing in NodeJS

Published Mar 08, 2023Last updated Apr 18, 2023
Built-in Testing in NodeJS

Node is pulling in more features into the base experience, and one of those is a built-in test runner and assertion/testing API. This is still experimental as of Node 19, but exciting none the less.

Note that this is available in Node 18 LTS and forward.

To get started just create a test file, e.g. test.mjs, and import the test API.

import test from 'node:test';

Note the new import prefix node:. This only works with that prefix, signifying that it's a built-in feature and not an npm module.

import test from 'node:test';
import assert from 'node:assert';
import getUserById from '../user';

test("asynchronous passing test", async (t) => {
  const user = await getUserById(1);
  assert.equal(user.id, 1);
});

test("failed test", (t, done) => {
  setTimeout(() => {
    done(new Error("failed"));
  }, 100);
});

Now you can run this with node --test test.mjs. And you get something like this:

Screenshot 2023-03-07 at 10.43.29 PM.jpg

The test runner API is pretty robust, and returns the TAP format which is widely supported by other tools. The API even supports aliases for mocha, like describe and it. There is even a watch feature!

node --test --watch

Which will find all *.test.{mjs,cjs,js} files, and others, or you can just pass files you want to watch. This, mocks and many other features are part of this API. You basically have all you need to start testing without installing anything new. Give it a go and check out their docs, which are pretty good.


Looks like as of Node 20 the test runner is now stable: blog post announcing Node 20

Discover and read more posts from Ilya Radchenko
get started
post commentsBe the first to share your opinion
Show more replies