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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github