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:
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"
}
}
JSONEach line of package.json has one job:
"name"labels the project. Any lowercase name works."private": truestops the project being published to the npm registry by accident."type": "module"tells Node.js that.jsfiles in this folder useimportandexport. Without it, Node.js has to guess the module format for each file."scripts"defines shortcuts. With"test": "node --test", the commandnpm testruns 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:
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)}`;
}
JSLine by line:
export function applyDiscount(cents, percent)defines a function and makes it available to other files, including your test file.- The first
ifrefuses an amount that is not a whole number, or is negative, by throwing aTypeError. A thrown error stops the function, so bad input never produces a wrong price silently. - The second
ifrefuses a discount below 0 or above 100 per cent with aRangeError, the built-in error type for "this number is outside the allowed range". (cents * (100 - percent)) / 100keeps the part of the price the customer still pays. A 20 per cent discount keeps 80 per cent.formatAmountdivides by 100 to turn cents into the main unit, andtoFixed(2)always shows two decimal places, so 1500 becomes1500.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:
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:
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 testLine by line:
import { test } from 'node:test'loads the function that registers a test. Thenode:prefix means "built into Node.js", not a package from npm.import assert from 'node:assert/strict'loads the checking functions. The/strictversion compares with===, so'4000'(a string) does not count as equal to4000(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:
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)callsfnand passes only if it throws aRangeError. You pass a function,() => applyDiscount(5000, 150), not the result of calling it; otherwise the error would be thrown beforeassert.throwscould 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:
✖ 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 !== 849shows the actual value on the left and the expected value on the right.- The
at ... price.test.js:10:10line gives the file, line and column of the assertion that failed. Open the file at that line to see the call. actualandexpectedrepeat 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:
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 testThe 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:
node --test price.test.jsTo 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:
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:
cd ~
rm -rf ~/price-tests-demoCheck 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
- Run this suite automatically on every push: run Node.js tests in GitHub Actions.
- Learn more about the
importandexportlines you used: use JavaScript modules with import and export. - See the same ideas in Python: test Python code with pytest.
- The
node:testandnode:assertpages in the Node.js documentation at nodejs.org/api list the rest, includingdescribefor grouping tests,beforeEachfor shared set-up and mocking.
Related tutorials
- Write your first class in Python: objects, attributes and methodsYou will model a library book loan as a Python class with attributes, methods, a readable __repr__ and a shared loan period, compare it with a dictionary version, rewrite it as a dataclass and end with a Loan class and a short script that uses it.
- Write readable code: names, comments and a formatterYou will turn a working but cryptic Python script into a readable one with clear names, named constants, small functions and useful comments, tidy it with Ruff, prove its output has not changed and leave with your own style checklist.
- Write pseudocode before you codeYou will plan a bus-fare calculator in pseudocode, trace it by hand to find and fix a gap in the plan, draw it as a flowchart and turn it line by line into a Python script that gives the same answers.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials