HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptTip

Introduction to the Node.js test module

Submitted by: @import:30-seconds-of-code··
0
Viewed 0 times
javascripttestmodulenodetheintroduction

Problem

A little while back, I stumbled upon the Node.js test module. Having tried various JavaScript testing tools in recent years, I decided to set some time aside to test it and see how it works.
_Before you read any further, note that at the time of writing (April, 2023), this module is still experimental and is likely to change in future releases. While not recommended for production use, it's still worth learning about as it might come in handy later down the line._
So, how does the Node.js test module compare to the likes of Jest and Vitest? As expected, it's less feature-rich than other tools, which is understandable given that it's still in its early stages. However, the core functionality is there and it's very easy to use and set up as it doesn't require third-party dependencies.
Before you can use the module, you'll have to import it. You'll most likely have to import the assertion module as well. Here's how to import both:
Additionally, if you want to use methods such as describe or it from the test module, you'll have to import them as well. For example:

Solution

import test from 'node:test';
import assert from 'node:assert/strict';


So, how does the Node.js test module compare to the likes of Jest and Vitest? As expected, it's less feature-rich than other tools, which is understandable given that it's still in its early stages. However, the core functionality is there and it's very easy to use and set up as it doesn't require third-party dependencies.
Before you can use the module, you'll have to import it. You'll most likely have to import the assertion module as well. Here's how to import both:
Additionally, if you want to use methods such as describe or it from the test module, you'll have to import them as well. For example:
Now that you have the module imported, you can start writing tests. The test module provides a test function that takes two arguments in its simplest form:
  • name: a string describing the test
  • fn: a function containing the test logic

Code Snippets

import test from 'node:test';
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import test from 'node:test';
import assert from 'node:assert/strict';

test('my test', () => {
  assert.strictEqual(1, 1);
});

Context

From 30-seconds-of-code: nodejs-test-module-introduction

Revisions (0)

No revisions yet.