In Node.js, we have a lot of libraries and frameworks for testing. Testing is a fundamental part of software development, as it ensures that our code works as expected and helps us catch bugs before they reach production.
In this article, we will look at the native module node:test
, which is sufficient to cover the needs of small and medium projects.
Examples of the Test Module
Writing Unit Tests
The node:test
module allows us to define and run tests easily. Let’s see a simple example of how to write unit tests using this module:
// tests.mjs
import assert from 'node:assert';
import test from 'node:test';
test('that 1 is equal 1', () => {
assert.strictEqual(1, 1);
});
test('that throws as 1 is not equal 2', () => {
// throws an exception because 1 != 2
assert.strictEqual(1, 2);
});
In this example:
- We import the necessary modules:
assert
for making assertions andtest
for defining the tests. - Two tests are defined using the
test
function. Each test has a description as the first argument and a function containing the logic of the test as the second argument.- In the first test,
assert.strictEqual(1, 1)
is used to verify that the number 1 is strictly equal to 1. - In the second test,
assert.strictEqual(1, 2)
is used, which attempts to verify if 1 is strictly equal to 2, which is false.
- In the first test,
Running the Tests
To run the tests, simply execute the tests.mjs
file with Node.js:
node tests.mjs
The result of the tests will be displayed in the console.
- If all tests pass, you will see a message indicating that all assertions have been completed successfully. ✔️
- Otherwise, error messages will be displayed indicating which tests have failed and why. ❌
Additional Examples of Unit Tests
In addition to the basic tests, here are some additional examples you can add to cover more use cases:
test('Checking that true is true', () => {
assert.strictEqual(true, true);
});
test('Checking that false is false', () => {
assert.strictEqual(false, false);
});
test('Checking that 0 is falsy', () => {
assert.strictEqual(0, false);
});
test('Checking that "hello" is a string', () => {
assert.strictEqual(typeof "hello", 'string');
});
test('Checking that [1, 2, 3] contains the number 2', () => {
assert.deepStrictEqual([1, 2, 3].includes(2), true);
});
test('Checking that {a: 1, b: 2} has the property "a"', () => {
assert.strictEqual(Object.prototype.hasOwnProperty.call({a: 1, b: 2}, 'a'), true);
});
test('Checking that a function adds two numbers correctly', () => {
function add(a, b) {
return a + b;
}
assert.strictEqual(add(2, 3), 5);
});
Download the Code
All the code from this post is available for download on Github