The Node.js Test Runner
๐ Covered in this chapter:
Unit Tests ยท Assertions ยท Test Suites ยท Test Hooks ยท Async Tests
Write unit tests using Node's built-in test runner (node:test) โ no external testing framework required.
1The Node.js Test Runner โ What You'll Learn
Write unit tests using Node's built-in test runner (node:test) โ no external testing framework required.
Here's everything this chapter covers, in the order you'll learn it:
- What testing is and why it matters
- Unit tests
- Integration tests
- End-to-end tests (overview)
- Node's built-in test runner
- Organizing test files
- Assertions with node:assert
- Test suites (describe-like grouping)
- Test hooks (before/after)
- Mocking dependencies
- Testing async code
- Measuring test coverage
2Working Example
๐ป Example: The Node.js Test Runner
JavaScript
โถ Run in Compiler
import test from "node:test";
import assert from "node:assert/strict";
test("addition works", () => {
assert.equal(2 + 3, 5);
});
3Best Practices & Common Pitfalls
๐ก Key things to remember:
- Run tests with `node --test` โ no extra packages needed for basic unit testing since Node.js LTS ships node:test built in.
โ Frequently Asked Questions (FAQ)
Q What's the most important thing to understand about the node.js test runner?
Focus on: Unit Tests ยท Assertions ยท Test Suites ยท Test Hooks ยท Async Tests. These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for the node.js test runner?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.