Node.js
describe and it
Learn test organization with describe and it.
Grouping with describe
As tests multiply, grouping them with describe improves readability. describe("calculator", () => { test("add", ...); test("subtract", ...); }). describe takes a name and a callback; tests inside the callback form a group.
it is an alias for test. They mean the same; some teams prefer test, others it. Example: describe("math", () => { it("add", () => {}); }). Groups can be nested: a describe inside another describe. This breaks large test files into sections. In the output the group name prefixes the test name, so you quickly locate a failing test.
Nested groups
You can define a describe inside another describe. This is useful to break large features into sub-features. Example: describe("math", () => { describe("addition", () => { it("positive", () => {}); }); }).
The output shows the group hierarchy: math > addition > positive. This quickly shows which feature set a failing test belongs to. describe is only a visual grouping; at runtime tests still run in order. Tests inside a group can share a setup; we will do that with hooks in the next lesson. For now building the group structure is enough.
Exercise Group calculator tests
Import test, describe and it from node:test. Group two tests with describe("calculator", () => { it("add", () => {}); it("subtract", () => {}); }). Print "Grouped" with console.log.
Show example solution
const { test, describe, it } = require("node:test");
describe("calculator", () => {
it("add", () => {});
it("subtract", () => {});
});
console.log("Grouped");
Test yourself
-
Match each piece to its role
- describe
- Defines a test group
- it
- Alias for test
- test
- Defines a single test
- () => {}
- Arrow function body
-
What is the relationship between it and test?
test("x", () => {}); // it("x", () => {})
- it runs faster
- test checks more strictly
- it is another name for test
- test only works inside describe
Show answer
it is another name for test — it is a synonym for test.
-
Complete the describe call
describe("hesap", ____ () => { it("topla", () => {}); });
Show answer
describe("hesap", () => () => { it("topla", () => {}); });
Next lesson: Before and after