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
actualandexpectedvalues, which can confuse error messages. - Comparing objects or arrays without deep equality, but
assertEqualshandles deep checks correctly. - Not importing
assertEqualsfrom 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.tswith the latest stable version. - Use
assertEquals(actual, expected)to compare values deeply. - Use inside
Deno.testblocks 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.