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 testcommand. - Writing asynchronous tests without returning or awaiting Promises.
- Using
console.loginstead 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 Function | Purpose |
|---|---|
| Deno.test(name, fn) | Defines a test case with a name and function |
| assertEquals(actual, expected) | Checks if two values are equal |
| deno test | Runs all test files in the current directory |
| --allow-net | Flag to allow network access if your test needs it |
| --unstable | Flag 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.