Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 37 ยท Testing and Tooling

Testing in Deno with deno test

Write tests with Deno.test, group them in steps, filter and parallelize runs, read coverage reports, test servers by calling handlers and measure speed with deno bench. No extra tools needed.

Deno ships with a test runner. There is nothing to install, no config file to write and no choice between five frameworks: you call Deno.test, you run deno test. The runner finds files, runs every test, reports failures with readable diffs, can measure coverage, and works with TypeScript out of the box.

This lesson covers writing tests, organizing them with steps, controlling what runs, and measuring coverage and speed. The next lesson, Assertions, BDD and Mocking, covers the standard library helpers that make tests short and expressive.

Deno does not run on this site, so Deno.* and jsr: code is read-only. The runnable blocks use a 25-line stand-in for Deno.test written in plain Node, so you can see how a test runner behaves: it collects tests, runs them one by one, catches failures and reports. The shape of your tests is identical in real Deno.

Your first test

Create math.ts and a test file next to it:

TypeScript
// math.ts
export function add(a: number, b: number): number {
  return a + b;
}
TypeScript
// math_test.ts
import { assertEquals } from "jsr:@std/assert";
import { add } from "./math.ts";

Deno.test("add sums two numbers", () => {
  assertEquals(add(2, 3), 5);
});

Deno.test("add handles negatives", () => {
  assertEquals(add(-2, -3), -5);
});
Terminal
deno test
TEXT
running 2 tests from ./math_test.ts
add sums two numbers ... ok (1ms)
add handles negatives ... ok (0ms)

ok | 2 passed | 0 failed (12ms)

A test passes when its function returns (or its promise resolves) without throwing. It fails when it throws, usually because an assertion failed. That is the whole model.

Which files are tests?

deno test (with no arguments) looks in the current folder, recursively, for files named:

  • _test.{ts,tsx,js,jsx,mjs} or .test.{...}
  • test.{...}

You can also pass paths: deno test src/, or one file: deno test math_test.ts.

Async tests and the options form

Tests can be async. Return nothing special; just await inside:

TypeScript
Deno.test("reads a file", async () => {
  const text = await Deno.readTextFile("./fixtures/hello.txt");
  assertEquals(text.trim(), "hello");
});

The second form takes an options object when you need more control:

TypeScript
Deno.test({
  name: "talks to the network",
  ignore: Deno.build.os === "windows",     // skip on some platforms
  permissions: { net: ["localhost:8000"] }, // run with only this permission
  sanitizeOps: true,                        // fail on leaked async operations
  sanitizeResources: true,                  // fail on leaked open files/sockets
  fn: async () => {
    const res = await fetch("http://localhost:8000");
    await res.body?.cancel();               // always consume or cancel the body
  },
});
Option Effect
ignore: true skip the test (shown as ignored)
only: true run only this test (the run then fails as a reminder to remove it)
permissions run this test with a limited permission set
sanitizeOps fail if the test leaves timers or async operations running
sanitizeResources fail if the test leaks files or connections
sanitizeExit fail if the code under test calls Deno.exit()

The sanitizers are one of Deno's best features: a test that forgets to await a promise, or forgets to close a file, fails with a message that names the leak instead of hanging or corrupting another test.

Steps: grouping inside a test

t.step creates sub-tests that share setup:

TypeScript
Deno.test("user service", async (t) => {
  const db = await openTestDatabase();

  await t.step("creates a user", async () => {
    const user = await db.create({ name: "Ada" });
    assertEquals(user.name, "Ada");
  });

  await t.step("finds the user", async () => {
    assertEquals((await db.find("Ada"))?.name, "Ada");
  });

  db.close();
});

Always await each step. Steps run in the order you write them, and output shows them nested under the parent. For a BDD style with describe, it and hooks (beforeEach, afterEach) see the next lesson.

See a runner work

Here is the stand-in runner. Read it as an explanation of what deno test does: it registers tests, runs them in order, catches thrown errors, supports ignore and steps, and prints a summary with a non-zero exit when something failed.

Node.js A tiny Deno.test 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.

Running tests: the flags you will use

Terminal
deno test                         # everything
deno test src/user_test.ts        # one file
deno test --filter "slugify"      # tests whose name contains the text
deno test --filter "/^add/"       # or match a regular expression
deno test --fail-fast             # stop at the first failure
deno test --parallel              # run test files concurrently
deno test --watch                 # re-run when files change
deno test --allow-net --allow-read=./fixtures
deno test --doc                   # also run code samples in JSDoc comments
deno test --junit-path=report.xml # JUnit XML for CI
deno test --shuffle               # random order to expose hidden dependencies

Tests run without permissions unless you pass them (or set permissions per test), just like normal programs. That also makes a test suite a safety net: if code under test unexpectedly reads the disk, the test fails loudly.

Testing an HTTP handler

Because handlers are plain functions, a handler test needs no server:

TypeScript
import { assertEquals } from "jsr:@std/assert";
import { handler } from "./server.ts";

Deno.test("GET /ping returns pong", async () => {
  const res = await handler(new Request("http://localhost/ping"));
  assertEquals(res.status, 200);
  assertEquals(await res.text(), "pong");
});

Export the handler from your module and start the server only when the file is the entry point (if (import.meta.main) Deno.serve(handler);), so tests can import the module without opening a port. The runnable example below applies this idea and also shows the typical test-data helpers.

Node.js Testing a handler and error cases

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 in a file run in the order they are defined and share module state, as here, so keep each test independent unless you intentionally build on earlier ones. Reset shared state in a setup step.

Coverage

Terminal
deno test --coverage=cov/
deno coverage cov/                  # text table per file
deno coverage cov/ --lcov > cov.lcov   # for Codecov, Coveralls, editors
deno coverage cov/ --html           # browsable report

Coverage shows which lines ran, not whether your assertions are good. Use it to find code your tests never touch, not as a score to maximize.

Benchmarks

deno bench runs functions many times and reports timings, with the same file rules (*_bench.ts or *.bench.ts):

TypeScript
Deno.bench("array spread", () => {
  const a = [1, 2, 3];
  [...a, 4];
});

Deno.bench({ name: "array concat", group: "append", baseline: true }, () => {
  [1, 2, 3].concat(4);
});

Benchmarks are for comparing two implementations on your machine, not for absolute claims. Run them with the same flags and no other heavy load.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a Deno.test pass?

    A thrown error (usually from a failed assertion) fails a test; returning normally passes it. The return value is ignored.
  2. 2. What does the sanitizeResources option catch?

    With sanitizeResources the runner fails a test that leaks open resources such as files, sockets or response bodies.
  3. 3. Which command runs only tests whose name contains 'slugify'?

    --filter matches the test name by substring, or by regular expression when written as /pattern/.
  4. 4. Why export the handler and only call Deno.serve when import.meta.main is true?

    Importing the module then has no side effects, so tests can call the handler directly with a Request.
  5. 5. Which flag produces a coverage report from a test run?

    deno test --coverage=dir writes raw data into the directory; deno coverage dir turns it into a report.

Summary

  • Deno.test(name, fn) registers a test; throwing fails it, returning passes it.
  • Use t.step to group, ignore, only and permissions to control, and the sanitizers to catch leaks.
  • Files named *_test.ts or *.test.ts are found automatically; --filter, --parallel, --fail-fast and --watch shape a run.
  • Handlers are functions: export them and test with new Request(...).
  • --coverage plus deno coverage shows untested code; deno bench compares speed.

Next: Assertions, BDD and Mocking