Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 37 ยท Testing and Tooling

Assertions, BDD and Mocking in Deno Tests

Use @std/assert for clear failures, describe and it with hooks from @std/testing/bdd, spies and stubs for mocking, FakeTime for timers and snapshots, with runnable stand-ins of each idea.

Deno.test runs your tests, but it does not decide what you check. That is the job of assertions: functions that throw a helpful error when a value is not what you expected. The standard library provides them in jsr:@std/assert, plus BDD-style structure, mocks, fake clocks and snapshots in jsr:@std/testing.

This lesson shows each tool and, because the real packages need Deno, includes small runnable stand-ins that behave the same way so you can see the mechanics: how deep equality works, how a spy records calls, and how a fake clock makes timers instant.

The assert module

TypeScript
import {
  assert,
  assertAlmostEquals,
  assertArrayIncludes,
  assertEquals,
  assertExists,
  assertInstanceOf,
  assertMatch,
  assertNotEquals,
  assertObjectMatch,
  assertRejects,
  assertStrictEquals,
  assertStringIncludes,
  assertThrows,
  fail,
} from "jsr:@std/assert";
Function Checks
assert(x, msg?) x is truthy
assertEquals(a, b) deep equality (objects, arrays, Maps, Sets, Dates)
assertStrictEquals(a, b) same value and type, like === (Object.is semantics)
assertNotEquals(a, b) the values differ
assertAlmostEquals(a, b, tol) numbers within a tolerance (floating point)
assertExists(x) not null or undefined
assertMatch(str, /re/) a string matches a pattern
assertStringIncludes(s, part) substring present
assertArrayIncludes(arr, items) arrays contain the items
assertObjectMatch(obj, subset) obj contains the subset of properties
assertInstanceOf(x, Class) class check, narrows the TypeScript type
assertThrows(fn, ErrorClass?, msg?) fn throws a matching error
assertRejects(fn, ErrorClass?, msg?) the async fn rejects (always await it)

A failing assertEquals prints a colored diff of the two values, which is why you should prefer it to assert(a === b): the second form can only tell you "false".

Never compare floats with assertEquals. 0.1 + 0.2 is not 0.3, so use assertAlmostEquals(0.1 + 0.2, 0.3, 1e-9).

What deep equality really does

Here is a compact stand-in for the core of assertEquals, with the assertions built around it. Study how it treats objects and why order matters for arrays but not for object keys.

Node.js Assertions from scratch (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

BDD style: describe, it and hooks

If you prefer the Mocha or Jest layout, jsr:@std/testing/bdd gives you describe, it, and lifecycle hooks, all built on Deno.test:

TypeScript
import { afterEach, beforeEach, describe, it } from "jsr:@std/testing/bdd";
import { assertEquals } from "jsr:@std/assert";
import { Cart } from "./cart.ts";

describe("Cart", () => {
  let cart: Cart;

  beforeEach(() => {
    cart = new Cart();
  });

  afterEach(() => {
    cart.clear();
  });

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

  describe("adding items", () => {
    it("sums prices", () => {
      cart.add({ name: "pen", price: 3 });
      cart.add({ name: "ink", price: 7 });
      assertEquals(cart.total(), 10);
    });

    it.ignore("applies coupons (TODO)", () => {});
  });
});

Hooks are beforeAll, beforeEach, afterEach and afterAll. Use beforeEach to build fresh state for every test so tests cannot depend on each other. Plain Deno.test with steps is just as valid; choose one style per project.

Mocking with spies and stubs

A spy wraps a function and records how it was called without changing behavior. A stub replaces behavior with something you control. Both come from jsr:@std/testing/mock:

TypeScript
import { assertSpyCall, assertSpyCalls, returnsNext, spy, stub } from "jsr:@std/testing/mock";

Deno.test("sendWelcome notifies once", () => {
  const send = spy((_to: string, _body: string) => {});
  const service = { send };

  sendWelcome(service, "[email protected]");

  assertSpyCalls(send, 1);
  assertSpyCall(send, 0, { args: ["[email protected]", "Welcome!"] });
});

Deno.test("fetchUser handles an API failure", async () => {
  const fetchStub = stub(globalThis, "fetch", returnsNext([
    Promise.resolve(new Response("boom", { status: 500 })),
  ]));
  try {
    await assertRejects(() => fetchUser(1), Error, "500");
  } finally {
    fetchStub.restore();        // always put the real function back
  }
});

stub(object, "method", replacement) temporarily swaps a method; restore() undoes it. Forgetting to restore leaks the fake into other tests, so use try/finally.

The stand-in below shows how little magic a spy needs: it is a function that remembers its calls.

Node.js How a spy and a stub work

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Tests with stubs never touch the network, so they are fast and stable. Stub at the edges of your program (HTTP, clock, random, file system), not deep inside your own logic: mocks that mirror your implementation make refactoring painful.

Fake time

Timers make tests slow and flaky. FakeTime from jsr:@std/testing/time replaces setTimeout, setInterval and Date with a clock you advance by hand:

TypeScript
import { FakeTime } from "jsr:@std/testing/time";
import { assertEquals } from "jsr:@std/assert";

Deno.test("debounce waits 300ms", () => {
  using time = new FakeTime();          // restored automatically at block end
  const calls: string[] = [];
  const save = debounce((v: string) => calls.push(v), 300);

  save("a");
  save("ab");
  time.tick(299);
  assertEquals(calls, []);              // not yet
  time.tick(1);
  assertEquals(calls, ["ab"]);          // only the last value, after 300ms
});

using (explicit resource management) disposes the fake clock when the test scope ends, even if an assertion throws. Without it, call time.restore() in finally.

Snapshot tests

assertSnapshot from jsr:@std/testing/snapshot stores a value on the first run and compares against it later. It suits large, stable outputs (rendered HTML, generated config):

TypeScript
import { assertSnapshot } from "jsr:@std/testing/snapshot";

Deno.test("renders a card", async (t) => {
  await assertSnapshot(t, renderCard({ title: "Deno" }));
});
Terminal
deno test --allow-read --allow-write -- --update    # create or refresh snapshots
deno test --allow-read                              # compare

Review snapshot diffs like code: a blindly updated snapshot proves nothing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why use assertAlmostEquals(0.1 + 0.2, 0.3, 1e-9) instead of assertEquals?

    0.1 + 0.2 is 0.30000000000000004 in binary floating point, so numeric tests need a tolerance.
  2. 2. What is the difference between a spy and a stub?

    A spy observes how a function is used; a stub substitutes its implementation with something you control.
  3. 3. What must you always do after stubbing a global like fetch?

    An unrestored stub leaks into other tests. Use try/finally or a hook to call restore().
  4. 4. What does assertRejects need that assertThrows does not?

    assertRejects returns a promise. Without await the test can finish before the assertion runs.

Summary

  • jsr:@std/assert gives assertEquals (deep), assertStrictEquals, assertThrows, assertRejects, assertAlmostEquals and more, each with a clear failure message.
  • describe, it and hooks from @std/testing/bdd provide a Mocha-style layout over Deno.test.
  • Spies record calls, stubs replace behavior; restore stubs in finally.
  • FakeTime makes timers and dates deterministic; assertSnapshot guards large outputs.
  • Mock the edges (network, time, files), not your own internals.

Next: Formatting, Linting and Type Checking