0
0
DenoHow-ToBeginner ยท 3 min read

How to Run Tests in Deno: Simple Guide with Examples

To run tests in Deno, write test functions using Deno.test() and then run deno test in your terminal. This command automatically finds and executes all test cases in your project files.
๐Ÿ“

Syntax

The basic syntax to define a test in Deno uses the Deno.test() function. It takes a test name and a function that contains your test code.

  • Deno.test(name, fn): Defines a test where name is a string describing the test, and fn is a function with the test logic.
  • assert functions from std/testing/asserts.ts help check conditions inside tests.
  • Run tests by executing deno test in the terminal, which finds all tests and runs them.
typescript
import { assertEquals } from "https://deno.land/std@0.203.0/testing/asserts.ts";

Deno.test("example test", () => {
  const actual = 1 + 1;
  const expected = 2;
  assertEquals(actual, expected);
});
๐Ÿ’ป

Example

This example shows a simple test that checks if adding two numbers equals the expected result. Running deno test will execute this test and show if it passed or failed.

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

Deno.test("addition works correctly", () => {
  const sum = 5 + 7;
  assertEquals(sum, 12);
});
Output
running 1 test ok 1 addition works correctly test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
โš ๏ธ

Common Pitfalls

Some common mistakes when running tests in Deno include:

  • Not importing assertion functions like assertEquals, causing errors inside tests.
  • Forgetting to run tests with deno test and trying to run test files with deno run instead.
  • Not using async when testing asynchronous code, which can cause tests to pass incorrectly or hang.

Always use deno test to run tests and import asserts from the standard library.

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

// Wrong: missing assert import
Deno.test("wrong test", () => {
  const result = 2 + 2;
  // assertEquals not imported, this will cause error
  // assertEquals(result, 4);
});

// Right:
Deno.test("correct test", () => {
  const result = 2 + 2;
  assertEquals(result, 4);
});
๐Ÿ“Š

Quick Reference

Command or FunctionDescription
Deno.test(name, fn)Defines a test with a name and test function
deno testRuns all tests in the current directory and subdirectories
assertEquals(actual, expected)Checks if two values are equal in a test
--allow-netFlag to allow network access if your tests need it
--unstableFlag to enable unstable Deno APIs if needed in tests
โœ…

Key Takeaways

Use Deno.test() to define tests and deno test to run them.
Import assertion helpers like assertEquals from Deno's standard library.
Run tests with deno test, not deno run.
Use async functions in tests when testing asynchronous code.
Add necessary permissions flags if your tests require them.