Summary - Testing basics
- Node.js course
- Intermediate
- Lesson 87/116
- 5 min
Combine node:test, assert and mock to write a calculator test.
Summary - Testing basics
In this group you learned Node.js's built-in testing tools: the node:test framework, assert assertions, grouping with describe and it, before/after hooks, and fake functions with mock. Now we will combine them in a calculator test.
Structure: a describe("calculator") group with a before hook for setup, it("add") and it("subtract") tests using assert.equal, and a mock.fn() fake logger. This is a small example of what a real project's test file looks like. Tests are run with node --test file.js; the output shows a TAP-style report.
Practice Write the calculator test
Import test, describe, before and mock from node:test, and also node:assert. Define function add(a, b) { return a + b; }. Create a fake logger with const log = mock.fn();. Write describe("calculator", () => { before(() => {}); test("add", () => { assert.equal(add(2, 3), 5); }); }). Print with console.log("Calculator test ready, mock: " + log.mock.calls.length).
Starter code
// Import test, describe, before and mock
// Also import assert
// write here
// Define the add function
// write here
// Create a fake logger
// write here
// Build a test group with describe
// write here
// Print "Calculator test ready, mock: ..."
// write hereSample solution
const { test, describe, before, mock } = require("node:test");
const assert = require("node:assert");
function add(a, b) { return a + b; }
const log = mock.fn();
describe("calculator", () => {
before(() => {});
test("add", () => {
assert.equal(add(2, 3), 5);
});
});
console.log("Calculator test ready, mock: " + log.mock.calls.length);Expected output
Hesap makinesi testi hazır, mock: 0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the correct way to add setup to a test group?
describe('x', () => { /* ... */ })- Adding before() inside describe Correct answer
- Printing with console.log
- Calling test() outside the group
- assert.equal kullanmamak
Explanation: The before hook runs setup before the group.
2 Match each concept to its role
| Term | Meaning |
|---|---|
test |
Defines a single test |
assert.equal |
Compares two values |
describe |
Groups tests |
mock.fn |
Creates a fake function |
3 Complete the multi-import
const { test, describe, before, ____ } = require("node:test");
const { test, describe, before, mock } = require("node:test");
Explanation: mock is also imported from node:test.