In Node.js, we have a ton of libraries and frameworks for testing. Tests are a fundamental part of software development, as they ensure our code works as expected and help us detect errors before they reach production.
In this article, we will look at the native node:test module, which is sufficient to cover the needs of small and medium-sized 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:
assertfor making assertions andtestfor defining tests. - Two tests are defined using the
testfunction. Each test has a description as the first argument and a function containing the test logic 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 test results will be displayed in the console.
- If all tests pass, you will see a message indicating that all assertions have completed successfully. ✔️
- Otherwise, error messages will be shown indicating which tests failed and why. ❌
Additional Unit Test Examples
In addition to 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
