Skip to main content

Programming fundamentals · Beginner · 14 min

Write your first JavaScript tests with the built-in Node.js test runner

By Padding · Updated 18 Nov 2026
Node.js 26.13 LTS · node:26 image

You will write a small price module in JavaScript, cover it with six passing tests using node:test and node:assert, and know how to read a failure and run one test on its own, with no packages installed.

On this page

A test is a small piece of code that calls your code with a known input and checks the answer. When every test passes, you know those inputs still give the answers you expect. When you change something later and a test fails, you find out before your users do.

Node.js has its own test runner. The node:test module gives you the test function, node:assert gives you the checks, and node --test finds and runs your test files. There is no framework to install, which also means no node_modules folder to download on a slow or prepaid connection.

In this tutorial you write price.js, a module with two functions for a shop: one applies a percentage discount and one formats an amount for display. You then write price.test.js, watch one test fail, read what the failure tells you, fix the code, and finish with six passing tests. Commands are shown for a Linux or macOS shell; on Windows, PowerShell runs the node commands the same way.

Step 1 · Set up an empty project

Check your Node.js version, then make a folder for the project and add a package.json file:

Bash
node --version
mkdir -p ~/price-tests-demo
cd ~/price-tests-demo
cat > package.json <<'JSON'
{
  "name": "price-tests-demo",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "node --test"
  }
}
JSON

Each line of package.json has one job:

  • "name" labels the project. Any lowercase name works.
  • "private": true stops the project being published to the npm registry by accident.
  • "type": "module" tells Node.js that .js files in this folder use import and export. Without it, Node.js has to guess the module format for each file.
  • "scripts" defines shortcuts. With "test": "node --test", the command npm test runs the test runner.

There is no "dependencies" section. Everything this tutorial uses ships with Node.js.

Check it worked

node --version prints a version starting with v26., such as v26.13.1. Run ls in ~/price-tests-demo and you see one file, package.json.

Step 2 · Write the price module

Shops store money as whole numbers of the smallest unit (cents, kobo, pesewas) rather than as decimals, because computers cannot store most decimal fractions exactly. 0.1 + 0.2 in JavaScript gives 0.30000000000000004. Working in cents avoids that, so both functions take an amount in cents.

Create price.js:

Bash
cat > price.js <<'JS'
export function applyDiscount(cents, percent) {
  if (!Number.isInteger(cents) || cents < 0) {
    throw new TypeError('cents must be a whole number of 0 or more');
  }
  if (percent < 0 || percent > 100) {
    throw new RangeError('percent must be between 0 and 100');
  }
  return (cents * (100 - percent)) / 100;
}

export function formatAmount(cents, currency) {
  return `${currency} ${(cents / 100).toFixed(2)}`;
}
JS

Line by line:

  • export function applyDiscount(cents, percent) defines a function and makes it available to other files, including your test file.
  • The first if refuses an amount that is not a whole number, or is negative, by throwing a TypeError. A thrown error stops the function, so bad input never produces a wrong price silently.
  • The second if refuses a discount below 0 or above 100 per cent with a RangeError, the built-in error type for "this number is outside the allowed range".
  • (cents * (100 - percent)) / 100 keeps the part of the price the customer still pays. A 20 per cent discount keeps 80 per cent.
  • formatAmount divides by 100 to turn cents into the main unit, and toFixed(2) always shows two decimal places, so 1500 becomes 1500.00. The template string puts the currency code in front.

This first version has a bug in it. You will let a test find it rather than spotting it by eye.

Try the functions once by hand:

Bash
node --input-type=module -e "import { applyDiscount, formatAmount } from './price.js'; console.log(applyDiscount(5000, 20), formatAmount(150000, 'NGN'));"

--input-type=module lets the one-line script given with -e use import.

Check it worked

The output is 4000 NGN 1500.00: 20 per cent off 5,000 cents is 4,000 cents, and 150,000 kobo shows as 1,500 naira.

Step 3 · Write and run your first test

Create price.test.js with one test:

Bash
cat > price.test.js <<'JS'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { applyDiscount, formatAmount } from './price.js';

test('applyDiscount takes 20% off 5000 cents to give 4000', () => {
  assert.strictEqual(applyDiscount(5000, 20), 4000);
});
JS
npm test

Line by line:

  • import { test } from 'node:test' loads the function that registers a test. The node: prefix means "built into Node.js", not a package from npm.
  • import assert from 'node:assert/strict' loads the checking functions. The /strict version compares with ===, so '4000' (a string) does not count as equal to 4000 (a number).
  • The third import loads the two functions under test from ./price.js.
  • test('...', () => { ... }) registers a test. The first argument is its name; the second is the code to run.
  • assert.strictEqual(actual, expected) throws an error if the two values differ. A test passes when its function finishes without throwing.

npm test runs node --test. With no file names, the runner searches the folder for files whose names match patterns such as *.test.js and runs each one.

Check it worked

The output starts with a line something like ✔ applyDiscount takes 20% off 5000 cents to give 4000 (0.8ms), followed by a summary that includes tests 1, pass 1 and fail 0.

Step 4 · Choose test cases and add five more

One passing test proves little. Good test cases come from three groups:

  • Normal: ordinary input a real customer sends. 15 per cent off 999 cents is one.
  • Boundary: the edges of what is allowed, where off-by-one mistakes live. For a discount, that is exactly 0 and exactly 100 per cent.
  • Invalid: input the function must refuse, such as a 150 per cent discount.

Name each test after the behaviour it checks, so a failure explains itself. applyDiscount rounds to the nearest cent tells you what broke; test 2 does not.

Replace price.test.js with the full suite:

Bash
cat > price.test.js <<'JS'
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { applyDiscount, formatAmount } from './price.js';

test('applyDiscount takes 20% off 5000 cents to give 4000', () => {
  assert.strictEqual(applyDiscount(5000, 20), 4000);
});

test('applyDiscount rounds to the nearest cent', () => {
  assert.strictEqual(applyDiscount(999, 15), 849);
});

test('applyDiscount keeps the full price at 0% and gives 0 at 100%', () => {
  assert.strictEqual(applyDiscount(5000, 0), 5000);
  assert.strictEqual(applyDiscount(5000, 100), 0);
});

test('applyDiscount rejects a discount above 100%', () => {
  assert.throws(() => applyDiscount(5000, 150), RangeError);
});

test('formatAmount shows the currency code and two decimals', () => {
  assert.strictEqual(formatAmount(150000, 'NGN'), 'NGN 1500.00');
});

test('formatAmount pads amounts under one unit with a leading zero', () => {
  assert.strictEqual(formatAmount(5, 'KES'), 'KES 0.05');
});
JS
npm test || echo "npm test exited with status $?"

Two new pieces:

  • A test can hold more than one assertion. The boundary test checks both edges, and stops at the first one that fails.
  • assert.throws(fn, RangeError) calls fn and passes only if it throws a RangeError. You pass a function, () => applyDiscount(5000, 150), not the result of calling it; otherwise the error would be thrown before assert.throws could catch it.

The rounding test expects 849 because 85 per cent of 999 is 849.15 cents, and a price cannot contain a fraction of a cent.

Check it worked

The summary shows tests 6, pass 5 and fail 1, and the last line is npm test exited with status 1. A failing test makes the runner exit with a non-zero status, which is how scripts and CI services know the suite failed.

Step 5 · Read the failing test's output

Find the failure in the output. It looks something like this:

Text
✖ applyDiscount rounds to the nearest cent (1.2ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:

  849.15 !== 849

      at TestContext.<anonymous> (file:///home/you/price-tests-demo/price.test.js:10:10)
  ...
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: 849.15,
  expected: 849,
  operator: 'strictEqual'

Read it from the top:

  • The ✖ line names the failing test. A behaviour-shaped name already says what is wrong: the function does not round.
  • 849.15 !== 849 shows the actual value on the left and the expected value on the right.
  • The at ... price.test.js:10:10 line gives the file, line and column of the assertion that failed. Open the file at that line to see the call.
  • actual and expected repeat the two values, which helps when they are long strings or objects.

The test is right and the code is wrong: applyDiscount returns a fraction of a cent. Sometimes it is the other way round, and the expected value in the test is the mistake. Check both before you change anything.

Check it worked

You can say in one sentence what failed and why: applyDiscount(999, 15) returned 849.15 instead of 849 because the result is never rounded.

Step 6 · Fix the code and see six passing tests

Rewrite price.js with the result rounded to a whole number of cents:

Bash
cat > price.js <<'JS'
export function applyDiscount(cents, percent) {
  if (!Number.isInteger(cents) || cents < 0) {
    throw new TypeError('cents must be a whole number of 0 or more');
  }
  if (percent < 0 || percent > 100) {
    throw new RangeError('percent must be between 0 and 100');
  }
  return Math.round((cents * (100 - percent)) / 100);
}

export function formatAmount(cents, currency) {
  return `${currency} ${(cents / 100).toFixed(2)}`;
}
JS
npm test

The only change is Math.round(...) around the calculation. It rounds to the nearest whole number, so 849.15 becomes 849 and 849.5 would become 850. Shops sometimes round discounts down instead, in the customer's favour; if yours does, use Math.floor and change the test to match. The test records the rule you chose.

Check it worked

Every line starts with ✔, the summary shows tests 6, pass 6 and fail 0, and npm test exits without an error.

Step 7 · Run one file or one test

As a project grows, you often want to run part of the suite. Give node --test a file name to run only that file:

Bash
node --test price.test.js

To run tests by name, pass --test-name-pattern with part of the name. The pattern is a regular expression, but plain words work as you expect:

Bash
node --test --test-name-pattern="rounds"

Only applyDiscount rounds to the nearest cent runs; the other five tests are left out of the run. Use this while you work on one failing test, then run the whole suite again before you finish, because a fix for one test can break another.

When you no longer need the project, delete it:

Bash
cd ~
rm -rf ~/price-tests-demo

Check it worked

node --test price.test.js shows six passing tests. The --test-name-pattern="rounds" run shows pass 1 and fail 0 in its summary. After the last command, ls ~/price-tests-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.