Node.js Intermediate: Express, Validation, SQLite and Tests
Testing with the Node Test Runner
In this lesson you will
- Write and run tests with node:test and assert
- Test an HTTP API by starting it on a free port
- Decide what to test and keep tests reliable
Introduction
Tests are code that checks your code. They let you change things with confidence, because a broken feature shows up in seconds instead of in front of users. Node includes a test runner, so you need no extra packages to start.
A first test
Save it as add.test.js and run:
Terminal
node --testA real run reports:
✔ adds numbers (0.6771ms)
✔ async works (0.128ms)
✔ throws on bad JSON (0.4241ms)with three passing tests and no failures. node --test finds files named like *.test.js and runs them. Use node --test --watch to re-run when files change.
test(name, fn)defines a test, and it fails if the function throws.assertfromnode:assert/strictgives checks such asequal,deepEqual,throwsandrejects. Use the strict version.
Quick quiz
When does a test defined with node:test fail?
Testing an HTTP API
Start your app on a free port, call it with fetch, and close it afterwards:
To make this possible, put app.listen in a separate file, so tests can import the app without starting a server on a fixed port. Using database :memory: for tests keeps them fast and isolated.
What to test
- The main paths: create, read, update, delete
- Invalid input: every validation rule you wrote
- Missing things: 404 cases
- Errors: that clients get safe, consistent responses
- Pure logic: small functions with tricky rules, such as price calculations
Do not test the framework or libraries themselves, and do not test private details that change often.
Keeping tests reliable
- Each test should set up its own data and not depend on other tests running first.
- Reset the database or state between tests.
- Avoid fixed waits such as "sleep two seconds". Wait for conditions instead.
- Avoid real network calls to other services. Use fakes or local servers.
- Make failures clear, with a descriptive test name.
- Run tests in a continuous integration pipeline on every change, so problems are caught early.
Try it yourself
Write tests for your to-do API covering: listing, creating, rejecting invalid input, getting a missing todo (404) and deleting. Make one assertion fail on purpose to see how failures are reported, then fix it.
Summary
node --testruns tests written withnode:testand strict assertions, with no extra packages.- Test APIs by starting the app on port 0 and calling it with fetch.
- Test main paths, bad input and errors, keep tests independent, and run them automatically.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading