node:test
- Node.js course
- Intermediate
- Lesson 82/116
- 5 min
Learn the built-in node:test test framework.
The node:test framework
Node.js ships with a built-in test framework: node:test. You do not need to install a separate package; just write require("node:test"). Run tests with node --test file.js.
The core function is test(). It takes a name and a callback. Inside the callback you make assertions with assert. Example: test("add", () => { assert.equal(1 + 1, 2); }). The test name helps you see which test failed in the output. In this lesson we only meet the structure of test(); the following lessons add assert, describe and mock.
Importing and structure
To import test from node:test you use destructuring: const { test } = require("node:test");. The curly braces extract the exported test variable from the module.
Structure: test("name", () => { /* body */ }). The callback is usually an arrow function; () => {...} is short and readable. The test body can run sync code, throw errors or make assertions. In this lesson we leave the body empty and only build the skeleton; later lessons fill the body. We print a line to confirm the program runs.
Practice Define your first test
Import test from node:test. Define a test with test("first test", () => {}). Print "Test defined" with console.log.
Starter code
// Import test from node:test
// write here
// Define a test
// write here
// Print "Test defined"
// write hereSample solution
const { test } = require("node:test");
test("first test", () => {
// test body
});
console.log("Test defined");Expected output
Test tanımlandı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does test() do?
test("topla", () => {})- Testi siler
- Defines a test function Correct answer
- Renames the test
- Runs and stops the test automatically
Explanation: test() takes a name and a callback and defines a test.
2 Complete the import line
const { test } = require(____);
const { test } = require("node:test");
Explanation: test is imported from the node:test module.
3 Match each piece to its role
| Term | Meaning |
|---|---|
test |
Defines a test function |
require |
Imports a module |
node:test |
Built-in test module |
() => {} |
Arrow function body |