Unit Testing with the Node.js Test Runner (node:test)

You do not need to install anything to write real unit tests in JavaScript: Node.js ships with a complete test runner, node:test, plus an assertion library, node:assert. It runs tests in parallel, supports async code, hooks, mocking, fake timers, snapshots and code coverage, and prints reports for CI. For testers moving from manual to automation, unit tests are the base of the test pyramid and the fastest feedback you can get. In this lesson you will write and run tests, use the most important assertions, test async code and errors, organise tests with describe and hooks, mock functions, methods and timers, and add snapshots, coverage and CI reporters. Every example was run with node --test on Node.js 26; the durations in brackets change from run to run.

Advertisement

📖 What You’ll Learn: what unit tests are and where they sit in the test pyramid, writing tests with test(), describe and it, running them with node –test, node:assert/strict (equal, deepEqual, throws, rejects, match), testing async code, testing errors, hooks (before, after, beforeEach, afterEach), skip, todo and only, filtering by name, mock.fn and mock.method, fake timers, snapshot tests, code coverage, reporters such as spec, dot, tap and junit, watch mode, and a tester checklist for good unit tests.


🧪 Unit Tests and the Test Pyramid

Definition: a unit test checks one small piece of code, usually a function or class, in isolation: given these inputs, it must return this output or throw this error. Unit tests run in milliseconds, need no browser or server, and pinpoint exactly what broke.

LevelTestsSpeedTools in this course
Unit (many)Functions and classes in isolationMillisecondsnode:test, Jest, Vitest
Integration / API (some)Modules and services working together, HTTP APIsSecondsnode:test with fetch, Playwright request
End-to-end UI (few)Real user flows in a real browserSeconds to minutesPlaywright

A healthy suite has many fast unit tests, fewer API tests and a focused set of end-to-end tests. Most bugs in calculations, validation and data handling are cheaper to catch at the unit level.


▶️ Your First Test

Import test from node:test and an assertion library, and write each test as a named function. The code under test lives in its own module:

📄 package.json

{ "type": "module" }

📄 cart.js

export function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

export function applyCoupon(total, code) {
  if (code === "SQA10") return total * 0.9;
  if (code === "FLAT100") return Math.max(total - 100, 0);
  throw new Error(`Invalid coupon: ${code}`);
}

📄 cart.test.js

import { test } from "node:test";
import assert from "node:assert/strict";
import { calculateTotal, applyCoupon } from "./cart.js";

test("adds price × qty for every item", () => {
  const items = [{ price: 499, qty: 2 }, { price: 799, qty: 1 }];
  assert.equal(calculateTotal(items), 1797);
});

test("returns 0 for an empty cart", () => {
  assert.equal(calculateTotal([]), 0);
});

test("SQA10 gives 10% off", () => {
  assert.equal(applyCoupon(1000, "SQA10"), 900);
});

⌨️ Terminal

node --test cart.test.js

🖥️ Output

✔ adds price × qty for every item (1.4537ms)
✔ returns 0 for an empty cart (0.1786ms)
✔ SQA10 gives 10% off (1.608ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 147.5327
  • node --test with no file names finds test files automatically: names like *.test.js, *-test.js, *_test.js and files in a test folder.
  • Each test file runs in its own process, in parallel, so files cannot affect each other.
  • Add "test": "node --test" to package.json scripts and run npm test.

When an assertion fails, the runner shows the expected and actual values and the exact line:

📄 package.json

{ "type": "module" }

📄 cart.js

export function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

export function applyCoupon(total, code) {
  if (code === "SQA10") return total * 0.9;
  if (code === "FLAT100") return Math.max(total - 100, 0);
  throw new Error(`Invalid coupon: ${code}`);
}

📄 failing.test.js

import { test } from "node:test";
import assert from "node:assert/strict";
import { applyCoupon } from "./cart.js";

test("SQA10 gives 10% off", () => {
  assert.equal(applyCoupon(1000, "SQA10"), 850);   // wrong expectation on purpose
});

⌨️ Terminal

node --test failing.test.js

🖥️ Output

✖ SQA10 gives 10% off (2.0039ms)
ℹ tests 1
ℹ suites 0
ℹ pass 0
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 134.4572

✖ failing tests:

test at failing.test.js:5:1
✖ SQA10 gives 10% off (2.0039ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
  
  900 !== 850
  
      at TestContext.<anonymous> (file:///home/you/js-course/failing.test.js:6:10)
      at Test.runInAsyncScope (node:async_hooks:226:14) {
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: 900,
    expected: 850,
    operator: 'strictEqual',
    diff: 'simple'
  }

✅ Assertions with node:assert/strict

Always import node:assert/strict: it uses strict equality (=== semantics) everywhere. The non-strict version uses ==, so assert.equal(1, "1") would pass.

📄 package.json

{ "type": "module" }

📄 assertions.test.js

import { test } from "node:test";
import assert from "node:assert/strict";

test("the most useful assertions", () => {
  assert.equal(2 + 2, 4);                                     // same primitive value
  assert.notEqual("passed", "failed");
  assert.deepEqual({ id: 1, tags: ["smoke"] }, { id: 1, tags: ["smoke"] });   // same structure
  assert.ok([1, 2].includes(2));                              // truthy
  assert.match("Order #4521 placed", /#\d{4}/);               // regex
  assert.throws(() => JSON.parse("{bad"), SyntaxError);      // throws this error type
  assert.throws(() => { throw new Error("Invalid coupon: FREE"); }, { message: /Invalid coupon/ });
});

test("deepEqual explains what differs", () => {
  const actual = { name: "Asha", roles: ["tester"] };
  assert.deepEqual(actual, { name: "Asha", roles: ["tester", "admin"] });
});

⌨️ Terminal

node --test assertions.test.js

🖥️ Output

✔ the most useful assertions (1.9702ms)
✖ deepEqual explains what differs (1.5629ms)
ℹ tests 2
ℹ suites 0
ℹ pass 1
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 128.982

✖ failing tests:

test at assertions.test.js:14:1
✖ deepEqual explains what differs (1.5629ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
  + actual - expected
  
    {
      name: 'Asha',
      roles: [
        'tester',
  -     'admin'
      ]
    }
  
      at TestContext.<anonymous> (file:///home/you/js-course/assertions.test.js:16:10)
      at Test.runInAsyncScope (node:async_hooks:226:14) {
    generatedMessage: true,
    code: 'ERR_ASSERTION',
    actual: { name: 'Asha', roles: [ 'tester' ] },
    expected: { name: 'Asha', roles: [ 'tester', 'admin' ] },
    operator: 'deepStrictEqual',
    diff: 'simple'
  }
AssertionPasses when
equal(a, b) / notEqualObject.is(a, b) / not
deepEqual(a, b)Objects and arrays have the same content
ok(value)Value is truthy
match(text, regex)Text matches the pattern
throws(fn, expected)fn() throws (optionally a given class, message or object)
await rejects(promise, expected)The promise rejects
fail(message)Never: fails immediately

💡 Tip: Each test can also use t.assert (the same assertions bound to the test context), which is required for snapshot assertions shown later.


Advertisement

⏳ Async Tests and Errors

Make the test function async and await inside it; the runner waits for the promise. Use assert.rejects for promises that should fail. A real HTTP server on a free port keeps API tests realistic and self-contained:

📄 package.json

{ "type": "module" }

📄 api.test.js

import { test } from "node:test";
import assert from "node:assert/strict";
import http from "node:http";

const server = http.createServer((req, res) => {
  if (req.url === "/api/users/7") {
    res.writeHead(200, { "content-type": "application/json" });
    return res.end(JSON.stringify({ id: 7, name: "Asha" }));
  }
  res.writeHead(404).end();
});

async function getUser(base, id) {
  const res = await fetch(`${base}/api/users/${id}`);
  if (!res.ok) throw new Error(`GET /api/users/${id} -> ${res.status}`);
  return res.json();
}

test("user API", async (t) => {
  await new Promise((resolve) => server.listen(0, resolve));
  const base = `http://127.0.0.1:${server.address().port}`;
  t.after(() => server.close());                       // clean-up even if a subtest fails

  await t.test("returns an existing user", async () => {
    const user = await getUser(base, 7);
    assert.deepEqual(user, { id: 7, name: "Asha" });
  });

  await t.test("rejects for a missing user", async () => {
    await assert.rejects(getUser(base, 99), { message: "GET /api/users/99 -> 404" });
  });
});

⌨️ Terminal

node --test api.test.js

🖥️ Output

▶ user API
  ✔ returns an existing user (28.7967ms)
  ✔ rejects for a missing user (5.3143ms)
✔ user API (42.5564ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 208.8163

⚠️ Watch out: Forgetting await before assert.rejects(...) or before an async helper is the most common async testing bug: the test finishes before the check runs and passes even when the code is broken.


🗂️ describe, it and Hooks

Group related tests with describe (alias suite) and it (alias of test). Hooks run set-up and clean-up code: before/after once per group, beforeEach/afterEach around every test. Fresh data in beforeEach keeps tests independent:

📄 package.json

{ "type": "module" }

📄 cart-class.test.js

import { describe, it, before, beforeEach, afterEach, after } from "node:test";
import assert from "node:assert/strict";

class Cart {
  items = [];
  add(name, price) { this.items.push({ name, price }); }
  get total() { return this.items.reduce((s, i) => s + i.price, 0); }
}

describe("Cart", () => {
  let cart;
  before(() => console.log("before: once, e.g. start a server"));
  beforeEach(() => { cart = new Cart(); });            // a fresh cart for every test
  afterEach(() => console.log(`afterEach: cart had ${cart.items.length} item(s)`));
  after(() => console.log("after: once, e.g. stop the server"));

  it("starts empty", () => {
    assert.equal(cart.total, 0);
  });

  it("adds prices", () => {
    cart.add("Mouse", 799);
    cart.add("Cable", 499);
    assert.equal(cart.total, 1298);
  });

  describe("edge cases", () => {
    it("handles a free item", () => {
      cart.add("Sticker", 0);
      assert.equal(cart.total, 0);
    });
    it.todo("rejects negative prices");
    it.skip("applies regional tax", () => {});
  });
});

⌨️ Terminal

node --test cart-class.test.js

🖥️ Output

before: once, e.g. start a server
afterEach: cart had 0 item(s)
afterEach: cart had 2 item(s)
afterEach: cart had 1 item(s)
afterEach: cart had 0 item(s)
after: once, e.g. stop the server
▶ Cart
  ✔ starts empty (1.2103ms)
  ✔ adds prices (0.5986ms)
  ▶ edge cases
    ✔ handles a free item (1.2655ms)
    ✔ rejects negative prices (0.6458ms) # TODO
    ﹣ applies regional tax (0.1562ms) # SKIP
  ✔ edge cases (2.8761ms)
✔ Cart (7.6577ms)
ℹ tests 5
ℹ suites 2
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 1
ℹ todo 1
ℹ duration_ms 154.9909
NeedUse
Skip a test for nowit.skip(...) or { skip: "reason" }
Planned test, not written yetit.todo("...")
Run only some tests while debuggingit.only(...) plus node --test --test-only
Run tests whose name matchesnode --test --test-name-pattern="coupon"
Re-run on every file changenode --test --watch

🎭 Mocks, Spies and Fake Timers

A mock (or spy) replaces a real dependency so the test controls what it returns and records how it was called. node:test provides mock.fn() for new functions, mock.method() to replace a method on an existing object, and mock.timers to control time:

📄 package.json

{ "type": "module" }

📄 mocks.test.js

import { test, mock } from "node:test";
import assert from "node:assert/strict";

// code under test: depends on an email service and on time
function createSignup(emailService) {
  return async function signup(email) {
    if (!email.includes("@")) throw new Error("invalid email");
    await emailService.send(email, "Welcome to SQA Tools");
    setTimeout(() => emailService.send(email, "Your free cheat sheet"), 24 * 60 * 60 * 1000);
    return { email, status: "registered" };
  };
}

test("sends a welcome email immediately and a follow-up after 24 h", async (t) => {
  t.mock.timers.enable({ apis: ["setTimeout"] });
  const emailService = { send: async () => "sent" };
  const send = t.mock.method(emailService, "send");      // spy on the real method

  const signup = createSignup(emailService);
  const result = await signup("asha@sqatools.in");

  assert.deepEqual(result, { email: "asha@sqatools.in", status: "registered" });
  assert.equal(send.mock.callCount(), 1);
  assert.deepEqual(send.mock.calls[0].arguments, ["asha@sqatools.in", "Welcome to SQA Tools"]);

  t.mock.timers.tick(24 * 60 * 60 * 1000);              // a day passes instantly
  assert.equal(send.mock.callCount(), 2);
  assert.equal(send.mock.calls[1].arguments[1], "Your free cheat sheet");
});

test("does not email an invalid address", async (t) => {
  const send = t.mock.fn(async () => "sent");
  const signup = createSignup({ send });
  await assert.rejects(signup("not-an-email"), /invalid email/);
  assert.equal(send.mock.callCount(), 0);
});

test("mock.fn can return different values per call", (t) => {
  const flakyApi = t.mock.fn();
  flakyApi.mock.mockImplementationOnce(() => { throw new Error("503"); });
  flakyApi.mock.mockImplementation(() => "ok");
  assert.throws(() => flakyApi(), /503/);
  assert.equal(flakyApi(), "ok");
});

⌨️ Terminal

node --test mocks.test.js

🖥️ Output

✔ sends a welcome email immediately and a follow-up after 24 h (3.5317ms)
✔ does not email an invalid address (1.856ms)
✔ mock.fn can return different values per call (0.4257ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 151.0835

Mocks created with t.mock are restored automatically when the test ends, so they never leak into other tests. Mock only what is slow, unreliable or has side effects (email, payments, the clock, the network); over-mocking produces tests that pass while the real integration is broken.


Advertisement

📸 Snapshots, Coverage and Reporters

A snapshot test saves the output the first time (with --test-update-snapshots) and compares against it on later runs. It suits larger outputs such as generated reports or API payloads:

📄 package.json

{ "type": "module" }

📄 report.test.js

import { test } from "node:test";

function buildReport(results) {
  return {
    total: results.length,
    failed: results.filter((r) => r.status === "failed").map((r) => r.name),
  };
}

test("report shape", (t) => {
  t.assert.snapshot(buildReport([{ name: "login", status: "passed" }, { name: "cart", status: "failed" }]));
});

⌨️ Terminal

node --test --test-update-snapshots report.test.js

🖥️ Output

✔ report shape (1.737ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 195.5334

The snapshot is written to report.test.js.snapshot; commit it, and review snapshot changes in pull requests like code changes, since an accidental “update” can bless a bug.

Coverage shows which lines and branches the tests executed. It is a guide to untested code, not a quality score:

📄 package.json

{ "type": "module" }

📄 cart.js

export function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

export function applyCoupon(total, code) {
  if (code === "SQA10") return total * 0.9;
  if (code === "FLAT100") return Math.max(total - 100, 0);
  throw new Error(`Invalid coupon: ${code}`);
}

📄 coverage.test.js

import { test } from "node:test";
import assert from "node:assert/strict";
import { applyCoupon } from "./cart.js";

test("SQA10", () => assert.equal(applyCoupon(1000, "SQA10"), 900));
test("unknown coupon", () => assert.throws(() => applyCoupon(1000, "FREE")));

⌨️ Terminal

node --test --experimental-test-coverage coverage.test.js

🖥️ Output

✔ SQA10 (1.2956ms)
✔ unknown coupon (0.4133ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 145.1043
ℹ start of coverage report
ℹ ----------------------------------------------------------
ℹ file      | line % | branch % | funcs % | uncovered lines
ℹ ----------------------------------------------------------
ℹ cart.js   |  77.78 |    80.00 |   50.00 | 2-3
ℹ ----------------------------------------------------------
ℹ all files |  77.78 |    80.00 |   50.00 | 
ℹ ----------------------------------------------------------
ℹ end of coverage report

The report shows that lines 2–3 of cart.js (the body of calculateTotal) never ran, so only half the functions are covered, and branch coverage is 80% because no test used the FLAT100 coupon: two tests to add.

ReporterUseFlag
spec (default in a terminal)Readable tree for people--test-reporter=spec
dotCompact progress--test-reporter=dot
tapStandard machine format--test-reporter=tap
junitCI systems (Jenkins, GitLab, Azure)--test-reporter=junit --test-reporter-destination=results.xml
lcovCoverage for tools like Codecov--test-reporter=lcov with coverage enabled

🧪 Tester Scenario: Turning Test Cases into Unit Tests

A manual test-case table translates directly into a data-driven unit test. Here the boundary values for a password rule (8–20 characters, at least one digit and one uppercase letter) become one test per row:

📄 package.json

{ "type": "module" }

📄 password.test.js

import { describe, it } from "node:test";
import assert from "node:assert/strict";

function validatePassword(pw) {
  if (pw.length < 8) return "too short";
  if (pw.length > 20) return "too long";
  if (!/\d/.test(pw)) return "needs a digit";
  if (!/[A-Z]/.test(pw)) return "needs an uppercase letter";
  return "ok";
}

const cases = [
  ["Abcdef1", "too short", "7 chars: min - 1"],
  ["Abcdefg1", "ok", "8 chars: min"],
  ["Abcdefghijklmnopqrs1", "ok", "20 chars: max"],
  ["Abcdefghijklmnopqrst1", "too long", "21 chars: max + 1"],
  ["Abcdefgh", "needs a digit", "no digit"],
  ["abcdefg1", "needs an uppercase letter", "no uppercase"],
];

describe("validatePassword", () => {
  for (const [input, expected, why] of cases) {
    it(`${why} -> ${expected}`, () => {
      assert.equal(validatePassword(input), expected);
    });
  }
});

⌨️ Terminal

node --test password.test.js

🖥️ Output

▶ validatePassword
  ✔ 7 chars: min - 1 -> too short (2.2878ms)
  ✔ 8 chars: min -> ok (0.269ms)
  ✔ 20 chars: max -> ok (0.1609ms)
  ✔ 21 chars: max + 1 -> too long (0.1014ms)
  ✔ no digit -> needs a digit (0.094ms)
  ✔ no uppercase -> needs an uppercase letter (0.1025ms)
✔ validatePassword (4.3558ms)
ℹ tests 6
ℹ suites 1
ℹ pass 6
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 144.9471
  • One behaviour per test, with a name that says what should happen.
  • Arrange, Act, Assert: set up data, call the code, check the result.
  • Independent tests: fresh data per test, no reliance on order.
  • Cover boundaries and error paths, not just the happy path.
  • Fast and deterministic: mock the clock and the network.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write a test for isEven(n) that checks 2, 7 and 0.

Show answer

📄 package.json

{ "type": "module" }

📄 practice1.test.js

import { test } from "node:test";
import assert from "node:assert/strict";

const isEven = (n) => n % 2 === 0;

test("isEven", () => {
  assert.equal(isEven(2), true);
  assert.equal(isEven(7), false);
  assert.equal(isEven(0), true);
});

🖥️ Output

✔ isEven (1.0031ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 125.9695

Q2. Test that applyCoupon(1000, "FREE") throws an error whose message contains “Invalid coupon”.

Show answer

📄 package.json

{ "type": "module" }

📄 cart.js

export function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

export function applyCoupon(total, code) {
  if (code === "SQA10") return total * 0.9;
  if (code === "FLAT100") return Math.max(total - 100, 0);
  throw new Error(`Invalid coupon: ${code}`);
}

📄 practice2.test.js

import { test } from "node:test";
import assert from "node:assert/strict";
import { applyCoupon } from "./cart.js";

test("unknown coupon throws", () => {
  assert.throws(() => applyCoupon(1000, "FREE"), /Invalid coupon/);
});

🖥️ Output

✔ unknown coupon throws (1.0633ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 132.4186

Q3. Test an async function delayDouble(n) that resolves to n * 2 after 10 ms.

Show answer

📄 package.json

{ "type": "module" }

📄 practice3.test.js

import { test } from "node:test";
import assert from "node:assert/strict";

const delayDouble = (n) => new Promise((r) => setTimeout(() => r(n * 2), 10));

test("delayDouble", async () => {
  assert.equal(await delayDouble(21), 42);
});

🖥️ Output

✔ delayDouble (21.5384ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 153.3534

Q4. Use deepEqual to check that a function returns { status: "ok", items: [] }.

Show answer

📄 package.json

{ "type": "module" }

📄 practice4.test.js

import { test } from "node:test";
import assert from "node:assert/strict";

const emptyResponse = () => ({ status: "ok", items: [] });

test("empty response", () => {
  assert.deepEqual(emptyResponse(), { status: "ok", items: [] });
});

🖥️ Output

✔ empty response (3.4039ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 192.2324

Q5. Use t.mock.fn() to check that a notify callback is called exactly once with “done”.

Show answer

📄 package.json

{ "type": "module" }

📄 practice5.test.js

import { test } from "node:test";
import assert from "node:assert/strict";

function finish(notify) { notify("done"); }

test("notifies once", (t) => {
  const notify = t.mock.fn();
  finish(notify);
  assert.equal(notify.mock.callCount(), 1);
  assert.deepEqual(notify.mock.calls[0].arguments, ["done"]);
});

🖥️ Output

✔ notifies once (1.4851ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 125.5753

Q6. This test always passes, even when save() rejects. Why, and how do you fix it?

test("save fails for a bad id", () => {
  assert.rejects(save(-1));
});
Show answer

assert.rejects returns a promise. Without await (and an async test), the test function returns immediately and the runner never waits for the check. Fix: test("...", async () => { await assert.rejects(save(-1)); });


🧠 MCQ Quiz: Node.js Test Runner

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. How do you run tests with the built-in runner?
  2. Which import should you use for assertions?
  3. Which assertion compares objects by content?
  4. How do you test that a promise rejects?
  5. Which hook runs before every test in a describe block?
  6. How do you mark a test that is planned but not written?
  7. What does t.mock.method(obj, “send”) do?
  8. How do you make a 24-hour setTimeout run instantly in a test?
  9. Which flag shows code coverage?
  10. Which reporter is meant for CI systems such as Jenkins?

💼 Interview Questions and Answers

Q1. What makes a good unit test?

It tests one behaviour with a descriptive name, follows Arrange-Act-Assert, is independent of other tests and of execution order, is fast and deterministic (no real network, clock or randomness), covers boundaries and error paths, and fails with a message that explains the problem. It tests observable behaviour, not private implementation details, so refactoring does not break it.

Q2. Mock vs stub vs spy?

A stub replaces a dependency with canned responses (the API always returns this user). A spy records how a function was called, optionally still calling the real one. A mock is a stub with expectations about how it is used, verified by the test. In practice tools blur the terms: mock.fn() and jest.fn() can do all three.

Q3. Why use the Node.js test runner instead of Jest?

It needs no dependency or configuration, starts fast, runs files in parallel processes, works natively with ES modules and TypeScript type-stripping in recent Node.js, and includes mocks, fake timers, snapshots, coverage and CI reporters. Jest and Vitest still offer richer matchers, module mocking, watch-mode UIs and large ecosystems, so many projects keep them.

Q4. Is 100% code coverage a good goal?

No. Coverage shows which code ran, not whether it was checked correctly: a test without meaningful assertions can reach 100%. Use coverage to find untested areas (especially branches and error paths), set reasonable thresholds to prevent decline, and focus effort on risky business logic rather than chasing a number.


Advertisement

❓ Frequently Asked Questions

🤔 Can node:test run TypeScript tests?

Recent Node.js versions run .ts files directly by stripping type annotations, so node --test can pick up *.test.ts files for code that uses only erasable TypeScript syntax. Projects needing full TypeScript features use tsx or a build step.

🤔 Where should test files live?

Either next to the code (cart.js and cart.test.js) or in a test/ folder. Both are found automatically by node --test.

🤔 How do I run tests in CI?

Add "test": "node --test" to package.json, run npm ci and npm test in the pipeline, and use the junit reporter to publish results. A non-zero exit code fails the job.

🤔 Do I still need Playwright if I have unit tests?

Yes. Unit tests prove the pieces work; end-to-end tests prove the whole application works for a user in a real browser. The next lessons cover Jest/Vitest and the bridge to Playwright.


🏁 Summary

  • Unit tests check small pieces in isolation and form the fast base of the test pyramid.
  • Write tests with test/describe/it from node:test and run them with node --test.
  • Use node:assert/strict: equal, deepEqual, ok, match, throws, and await rejects for promises.
  • Hooks give fresh data per test; skip, todo, only and name patterns control what runs.
  • t.mock.fn, t.mock.method and mock timers isolate dependencies; snapshots, coverage and junit/lcov reporters support CI.

Next, continue with Lesson 70: Jest and Vitest.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in