0
0
DenoHow-ToBeginner ยท 4 min read

How to Use Test Coverage in Deno: Simple Guide

In Deno, you can measure test coverage by running deno test --coverage --unstable. This command runs your tests and collects coverage data, which you can then view with deno coverage --unstable to see which parts of your code were tested.
๐Ÿ“

Syntax

The basic syntax to run tests with coverage in Deno is:

  • deno test --coverage --unstable: Runs tests and collects coverage data.
  • deno coverage [directory] --unstable: Shows a coverage report for the collected data, optionally specifying the directory where coverage info is stored.

You can also specify output formats like --lcov or --json with deno coverage.

bash
deno test --coverage --unstable

deno coverage ./coverage --lcov --unstable > coverage.lcov
๐Ÿ’ป

Example

This example shows how to run tests with coverage and view a summary report.

typescript
/// example_test.ts
import { assertEquals } from "https://deno.land/std@0.203.0/testing/asserts.ts";

test("addition works", () => {
  assertEquals(1 + 1, 2);
});

test("string contains", () => {
  const str = "hello deno";
  if (!str.includes("deno")) {
    throw new Error("String does not contain 'deno'");
  }
});
๐Ÿ“Œ

Running Tests with Coverage

Run the tests and collect coverage data:

bash
deno test --coverage --unstable
Output
running 2 tests ok 1 addition works ok 2 string contains test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out To view coverage report, run: deno coverage --unstable
๐Ÿ“Œ

Viewing Coverage Report

After running tests with coverage, run this command to see a summary of coverage in your terminal:

bash
deno coverage --unstable
Output
example_test.ts Lines : 100.00% (10/10) Functions : 100.00% (2/2) Branches : 100.00% (0/0) Total coverage: 100.00%
โš ๏ธ

Common Pitfalls

  • Not using --unstable flag: Coverage features require the --unstable flag in Deno versions before full stabilization.
  • Forgetting to run deno coverage after tests: Running deno test --coverage only collects data; you must run deno coverage to see the report.
  • Coverage directory missing or deleted: Coverage data is stored in a directory (default ./coverage); deleting it before running deno coverage causes errors.
bash
Wrong:
denot test --coverage

Right:
deno test --coverage --unstable

deno coverage --unstable
โœ…

Key Takeaways

Use deno test --coverage --unstable to run tests and collect coverage data.
Run deno coverage --unstable to view the coverage report after testing.
Always include the --unstable flag when using coverage features in Deno.
Keep the coverage data directory intact until you finish viewing reports.
You can export coverage reports in formats like LCOV for integration with other tools.