Testing basics with the Node.js test runner
Course contents (16 lessons)
- Modern syntax
- Destructuring, spread and rest
- ES modules: import and export
- Objects, this and errors
- Classes and prototypes
- Understanding this in JavaScript
- Error handling: try, catch and custom errors
- Asynchronous JavaScript
- The event loop: how JavaScript handles waiting
- From callbacks to promises to async/await
- Fetch and REST APIs
- Working in the browser
- Local storage and session storage
- Debugging with browser DevTools
- Performance basics: debounce and throttle
- Node.js essentials
- Node.js and npm basics
- Working with files in Node.js
- A tiny HTTP server with Node.js
- Testing and the final project
- Testing basics with the Node.js test runner
- Final project: a post explorer with modules and fetch
Why write tests
Manual checking does not scale. Every time you change a function, you would have to try everything again by hand. A test is a small program that calls your code with known input and checks the output. Run them in a second after every change, and you find mistakes before your users do.
Tests also help you design. Code that is easy to test is usually code with small functions, clear inputs and clear outputs, which is the same advice we have followed all along.
The built-in test runner
Node.js includes a test runner, so you need no packages. You import test from node:test and assert from node:assert/strict.
Suppose we have a small module of price helpers. To keep this lesson in one file, the functions are at the top of the test file. In a real project they would be in their own file and you would import them.
import test from "node:test";
import assert from "node:assert/strict";
function applyDiscount(price, percent) {
if (price < 0) throw new RangeError("Price cannot be negative");
if (percent < 0 || percent > 100) throw new RangeError("Percent must be 0 to 100");
return Math.round(price * (100 - percent)) / 100;
}
async function fetchUserName(loadUser, id) {
const user = await loadUser(id);
return user.name.toUpperCase();
}
test("applyDiscount takes a percentage off", () => {
assert.equal(applyDiscount(200, 25), 150);
});
test("applyDiscount with 0 percent keeps the price", () => {
assert.equal(applyDiscount(99, 0), 99);
});
test("applyDiscount rejects a negative price", () => {
assert.throws(() => applyDiscount(-1, 10), RangeError);
});
test("fetchUserName uppercases the name", async () => {
const fakeLoadUser = async id => ({ id, name: "sara" });
const name = await fetchUserName(fakeLoadUser, 7);
assert.equal(name, "SARA");
});
test("fetchUserName passes the failure on", async () => {
const brokenLoadUser = async () => {
throw new Error("network down");
};
await assert.rejects(() => fetchUserName(brokenLoadUser, 1), /network down/);
});
Run it with node --test, or node yourfile.test.js. Node prints each test with a tick or a cross, and a summary. In a project, npm test can run node --test, which finds files that end in .test.js.
Anatomy of a good test
Each test follows the same three steps, called arrange, act, assert:
- Arrange. Prepare the input.
- Act. Call the code under test.
- Assert. Check the result.
Keep one idea per test, and give it a name that reads like a sentence, such as "applyDiscount rejects a negative price". When a test fails, its name should tell you what broke without opening the file.
The assertions you need
| Assertion | Use |
|---|---|
assert.equal(a, b) | Primitive values are equal (strict) |
assert.deepEqual(a, b) | Objects and arrays have the same content |
assert.ok(value) | Value is truthy |
assert.throws(fn, Type) | The function throws |
assert.rejects(promiseFn, ...) | The async function rejects |
Remember from the objects lesson that {} === {} is false. For objects use deepEqual:
assert.deepEqual({ a: 1, b: [2, 3] }, { a: 1, b: [2, 3] });
What to test
You cannot test everything, so pick well:
- The normal case with typical input.
- Edge cases: empty arrays, zero, empty strings, the first and last item.
- Invalid input, and that it is rejected in the right way.
- Every bug you fix. Write a test that fails because of the bug, fix the code, and watch it pass. That bug can never return unnoticed.
Do not test the language or libraries. You do not need a test proving that Array.prototype.map works.
Testing async code and avoiding the network
Notice the trick in the async tests. fetchUserName takes the loading function as a parameter, so the test passes a fake. The test is then fast, does not need the internet, and gives the same result every time. Tests that depend on a live API are slow and fail for reasons unrelated to your code. This idea, passing dependencies in rather than hard-coding them, is called dependency injection, and it is the most useful habit for testable code.
Grouping and setup
import { describe, it, beforeEach } from "node:test";
import assert from "node:assert/strict";
describe("shopping cart", () => {
let cart;
beforeEach(() => {
cart = []; // a fresh cart for every test
});
it("starts empty", () => {
assert.equal(cart.length, 0);
});
it("can add an item", () => {
cart.push({ id: 1 });
assert.equal(cart.length, 1);
});
});
beforeEach runs before every test so tests do not affect each other. Tests that depend on the order in which they run are fragile, and hard to debug.
Test-driven development in one paragraph
Some developers write the test first, watch it fail, then write the simplest code that passes. That is test-driven development. You do not have to follow it strictly, but writing a test first for a tricky function is a good way to think about the cases before you code.
Common mistakes
- Tests that never fail. Break the code on purpose once and confirm the test goes red.
- **Forgetting
awaiton async tests.** The test ends before the assertion runs. Make the test functionasyncandawaitthe call. - Testing implementation, not behaviour. If you rename an internal variable and tests break, they are too tightly tied.
- Depending on real time, random numbers or the network. Pass fakes in.
- One giant test. When it fails you will not know why.
- **Using
assert.equalon objects.** UsedeepEqual.
Try it yourself
- Write a function
isPalindrome(text)with at least five tests, including an empty string and mixed case. - Add a test for a bug:
applyDiscount(10, 33.333)should give a result rounded to two decimals. - Test the
debouncefunction from the earlier lesson. Hint: call it three times, wait a bit longer than the delay, and assert that the callback ran once. - Make a test fail on purpose and read the failure report that Node prints.
import test from "node:test";
import assert from "node:assert/strict";
function applyDiscount(price, percent) {
if (price < 0) throw new RangeError("Price cannot be negative");
if (percent < 0 || percent > 100) throw new RangeError("Percent must be 0 to 100");
return Math.round(price * (100 - percent)) / 100;
}
async function fetchUserName(loadUser, id) {
const user = await loadUser(id);
return user.name.toUpperCase();
}
test("applyDiscount takes a percentage off", () => {
assert.equal(applyDiscount(200, 25), 150);
});
test("applyDiscount with 0 percent keeps the price", () => {
assert.equal(applyDiscount(99, 0), 99);
});
test("applyDiscount rejects a negative price", () => {
assert.throws(() => applyDiscount(-1, 10), RangeError);
});
test("fetchUserName uppercases the name", async () => {
const fakeLoadUser = async id => ({ id, name: "sara" });
const name = await fetchUserName(fakeLoadUser, 7);
assert.equal(name, "SARA");
});
test("fetchUserName passes the failure on", async () => {
const brokenLoadUser = async () => {
throw new Error("network down");
};
await assert.rejects(() => fetchUserName(brokenLoadUser, 1), /network down/);
});
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account