0
0
DenoHow-ToBeginner ยท 3 min read

How to Write Tests in Deno: Simple Guide with Examples

In Deno, you write tests by importing assert functions from std/testing/asserts.ts and defining test cases with Deno.test(). Run tests using the deno test command in your terminal.
๐Ÿ“

Syntax

To write a test in Deno, use Deno.test() which takes a test name and a function containing your test code. Inside the function, use assertion functions like assertEquals() to check expected results.

  • Deno.test(name, fn): Defines a test with a descriptive name and a function.
  • assertEquals(actual, expected): Checks if two values are equal.
  • Tests run asynchronously if the function returns a Promise.
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 demonstrates a simple test that checks if adding two numbers returns the correct result. It uses Deno.test and assertEquals from Deno's standard library.

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

Common mistakes when writing tests in Deno include:

  • Not importing assertion functions from std/testing/asserts.ts.
  • Forgetting to run tests with deno test command.
  • Writing asynchronous tests without returning or awaiting Promises.
  • Using console.log instead of assertions to check results.

Always use assertions to make tests meaningful and reliable.

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

// Wrong: no assertion, test will always pass
Deno.test("wrong test", () => {
  const result = 2 * 3;
  console.log(result);
});

// Right: use assertion to verify result
Deno.test("correct test", () => {
  const result = 2 * 3;
  assertEquals(result, 6);
});
๐Ÿ“Š

Quick Reference

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

Key Takeaways

Use Deno.test() to define tests and import assertions from std/testing/asserts.ts.
Run tests with the deno test command in your terminal.
Always use assertions like assertEquals() to verify expected outcomes.
Write async tests by returning or awaiting Promises inside the test function.
Avoid relying on console.log; assertions make tests reliable and clear.