
Start testing with a function that has a clear boundary. A cart total takes structured input and returns an integer amount, so describing its behavior needs no browser, database, or mock server.
In the terminal you plan to use for testing, check node --version. The Node version manager exercise explains selecting Node 24, pinning an exact project version, and finding another executable earlier in PATH.
Use the built-in test runner
Run this on Node.js 24. Save the file as cart.test.mjs, then start it with node --test cart.test.mjs; nothing needs to be installed first. Prices are integer cents, and quantities must be positive safe integers.
import test from 'node:test';
import assert from 'node:assert/strict';
function totalCents(lines) {
if (!Array.isArray(lines)) throw new TypeError('expected cart lines');
let total = 0;
for (const line of lines) {
if (!line || !Number.isSafeInteger(line.cents) || line.cents < 0 ||
!Number.isSafeInteger(line.quantity) || line.quantity < 1)
throw new TypeError('invalid cart line');
total += line.cents * line.quantity;
if (!Number.isSafeInteger(total)) throw new RangeError('cart total is too large');
}
return total;
}
test('empty cart', () => assert.equal(totalCents([]), 0));
test('mixed cart', () => assert.equal(totalCents([
{cents:1250,quantity:2}, {cents:250,quantity:1}
]), 2750));
test('invalid input', () => {
for (const line of [{cents:1,quantity:0}, {cents:1,quantity:2.5},
{cents:Infinity,quantity:1}, {cents:'10',quantity:1}]) {
assert.throws(() => totalCents([line]), TypeError);
}
});
test('unsafe total', () => assert.throws(() => totalCents([
{cents:Number.MAX_SAFE_INTEGER,quantity:2}
]), RangeError));
Check the boundary, not the syntax
The suite contains four tests. It checks that an empty cart totals zero and that two distinct lines are multiplied and added correctly. It also rejects invalid quantities, a non-finite price, and a string price, then guards against totals outside JavaScript’s safe-integer range. Each test should pass.
Integer cents sidestep a familiar floating-point trap, such as summing decimal fractions for currency, but numeric limits remain. JavaScript numbers cannot represent every integer above the safe-integer range, so the function rejects any total it cannot represent exactly.
The Number.isSafeInteger checks also reject values such as 2.5, as the quantity contract requires. Shops selling fractional units need a different representation and validation policy. Don’t silently truncate quantities just to make the test pass.
Scroll sideways if the columns extend beyond the frame.
Input passed to totalCents |
Validation check triggered | Expected outcome |
|---|---|---|
[] (empty array) |
Array.isArray(lines) passes; loop runs 0 times |
Returns 0 (assert.equal(totalCents([]), 0)) |
[{cents:1250,quantity:2}, {cents:250,quantity:1}] |
Both lines pass safe-integer and range checks | Returns 2750 (2500 + 250) |
[{cents:1,quantity:0}] |
line.quantity < 1 |
Throws TypeError('invalid cart line') |
[{cents:1,quantity:2.5}] |
!Number.isSafeInteger(line.quantity) |
Throws TypeError('invalid cart line') |
[{cents:Infinity,quantity:1}] |
!Number.isSafeInteger(line.cents) |
Throws TypeError('invalid cart line') |
[{cents:'10',quantity:1}] |
!Number.isSafeInteger(line.cents) (no string coercion) |
Throws TypeError('invalid cart line') |
[{cents:Number.MAX_SAFE_INTEGER,quantity:2}] |
!Number.isSafeInteger(total) after multiplication |
Throws RangeError('cart total is too large') |
Make tests easy to trust and independent of implementation details
Every assertion in cart.test.mjs uses node:assert/strict and compares against a literal expected number (0, 2750) or a specific exception constructor (TypeError, RangeError). Importing node:assert/strict (or calling assert.strictEqual) guarantees that "2750" and 2750 are never treated as equal through loose type coercion. The tests also never derive the expected total by running lines.reduce(...) in the test file; copying the implementation’s formula into the test lets the same arithmetic or coercion bug hide on both sides of the assertion.
With IEEE-754 double precision, JavaScript represents every integer through Number.MAX_SAFE_INTEGER exactly (9007199254740991, or 2 ** 53 - 1). Larger integers may still be representable, but distinct neighbors can collapse to one value: Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 evaluates to true. Checking Number.isSafeInteger(total) after each iteration turns that risk into an explicit RangeError.
In this compact exercise, the function and its tests live in one .mjs file so you can run node --test cart.test.mjs right away. In a larger project, export totalCents from cart.mjs and import it into cart.test.mjs. Tests that stick to observable inputs and outputs let you refactor internal loops or helper functions without rewriting the suite.
Introduce one bug on purpose
Remove the quantity multiplication next. The mixed-cart test should fail, showing 1500 as the actual result instead of 2750. Restore the operation, then remove quantity validation and confirm the invalid-input test fails. These deliberate changes reveal whether the suite catches the failures that matter.
Avoid asserting on the exact wording of a diagnostic message unless callers rely on that wording. An exception type plus a stable error code usually makes a better public contract than prose written for a developer.
Know what remains outside the test
These tests can’t show whether a browser sends valid cart data, whether a server uses trustworthy prices, or whether checkout charges the correct amount. A real commerce service must validate data and own its prices on the server. This example tests a numeric function; it is not a payment system.
When you test an interactive task list, keep state changes apart from browser focus behavior. A unit test that passes says nothing about whether a keyboard user loses their place once the DOM is rebuilt. That check happens in the browser, and the DOM exercise walks through it.
You can apply the same approach to a small parser or validator in the notes API. Spell out the inputs, derive expected results independently of the implementation, and make each failure informative.
Source: Node.js test runner and assert document the standard-library testing tools.
Download the complete example. Save the file before running it; the guide above names the required runtime.
Keep building
- Pytest tutorial: test the edges of a small parser
Test a price parser with normal input, invalid input, and a temporary file instead of checking only the happy path.
- GitHub Actions for Python: a minimal test workflow
Run the same test command locally and in continuous integration with read-only permissions and an explicit Python version.
- How to contribute to open source with a small first patch
Choose a maintained project, reproduce one issue, and prepare a focused contribution that is easy to review.