0
0
DenoHow-ToBeginner ยท 3 min read

How to Use assertEquals in Deno for Testing

In Deno, use assertEquals(actual, expected) from the std/testing/asserts.ts module to check if two values are equal in tests. It throws an error if the values differ, helping you verify your code works as expected.
๐Ÿ“

Syntax

The assertEquals function takes two main arguments: actual and expected. It compares these values deeply and throws an error if they are not equal.

  • actual: The value your code produced.
  • expected: The value you expect.

You import it from Deno's standard testing library.

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

assertEquals(actual, expected);
๐Ÿ’ป

Example

This example shows a simple test function that checks if a sum function returns the correct result using assertEquals. If the values match, the test passes silently; if not, it throws an error.

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

function sum(a: number, b: number): number {
  return a + b;
}

Deno.test("sum adds two numbers correctly", () => {
  const result = sum(2, 3);
  assertEquals(result, 5);
});
Output
running 1 test ok 1 sum adds two numbers correctly test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
โš ๏ธ

Common Pitfalls

Common mistakes when using assertEquals include:

  • Swapping actual and expected values, which can confuse error messages.
  • Comparing objects or arrays without deep equality, but assertEquals handles deep checks correctly.
  • Not importing assertEquals from the correct URL or version.

Always ensure your expected value matches the actual output type and structure.

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

// Wrong: swapped arguments
// assertEquals(5, sum(2, 3)); // less clear error message

// Right:
assertEquals(sum(2, 3), 5);
๐Ÿ“Š

Quick Reference

Summary tips for using assertEquals in Deno:

  • Import from https://deno.land/std@0.203.0/testing/asserts.ts with the latest stable version.
  • Use assertEquals(actual, expected) to compare values deeply.
  • Use inside Deno.test blocks for automated testing.
  • Read error messages carefully to debug failed tests.
โœ…

Key Takeaways

Use assertEquals(actual, expected) from Deno's standard asserts module to compare values in tests.
Import assertEquals from the latest stable URL to avoid version issues.
Place assertEquals inside Deno.test blocks to run automated tests.
Ensure actual and expected values are in the correct order for clear error messages.
assertEquals performs deep equality checks for objects and arrays.