Language: EN

como-hacer-test-unitarios-nodejs

How to do unit tests in Node.js

Tests are a fundamental part of software development, as they ensure that our code works as expected and help us detect errors before they reach production.

In Node.js we have a lot of libraries and frameworks to do all kinds of tests. In this article we will see the native node:test module, which is sufficient to cover the needs of small and medium projects.

Module Test Examples

Writing Unit Tests

The node:test module allows us to define and execute tests in a simple way. 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 to make assertions and test to define the tests.
  • Two tests are defined using the test function. Each test has a description as the first argument and a function that contains 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 to verify if 1 is strictly equal to 2, which is false.

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 the tests pass, you will see a message indicating that all assertions have been successfully completed. ✔️

Otherwise, error messages indicating which tests have failed and why will be displayed. ❌

Additional examples of unit tests

In addition to the basic tests, here are some additional examples that 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 "a" property', () => {
  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);
});