How Do I Test a Single File Using Node Built-in Test Runner?

Better Stack Team
Updated on April 4, 2024

Node.js itself does not come with a built-in test runner. However, you can use the built-in assert module for simple assertion-based tests. If you want a more feature-rich test runner, you might consider using a third-party library like mocha or jest. Here, I'll show you a basic example using the assert module:

Write your test file

Let's say you have a module (math.js) with some functions you want to test:

 
// math.js
function add(a, b) {
  return a + b;
}

function subtract(a, b) {
  return a - b;
}

module.exports = { add, subtract };

Now, create a test file (test.js) for this module:

 
// test.js
const assert = require('assert');
const { add, subtract } = require('./math');

// Test the add function
assert.strictEqual(add(2, 3), 5, 'add function failed');

// Test the subtract function
assert.strictEqual(subtract(5, 2), 3, 'subtract function failed');

console.log('All tests passed!');

Run the test file

To run the test file, use the following command in your terminal:

 
node test.js

If all tests pass, you will see the message "All tests passed!".

This is a very basic example using Node.js's built-in assert module. For more advanced features, you might want to explore third-party test runners like mocha or jest. They offer features such as test organization, asynchronous testing, and test reporting. To use these libraries, you would typically install them via npm and configure your package.json to run your test files.