0
0
DenoHow-ToBeginner ยท 3 min read

How to Use Deno.test for Simple Testing in Deno

Use Deno.test to define a test by giving it a name and a function that contains your test code. Inside the function, use assertions like assertEquals to check expected results. Run tests with deno test in the terminal.
๐Ÿ“

Syntax

The Deno.test function takes an object with two main properties: name and fn. The name is a string describing the test, and fn is an async or sync function containing the test logic.

Inside fn, you write assertions to verify your code works as expected.

typescript
Deno.test({
  name: "test description",
  fn: () => {
    // test code here
  }
});
๐Ÿ’ป

Example

This example shows a simple test that checks if adding two numbers equals the expected result using assertEquals from Deno's standard testing asserts.

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

Deno.test({
  name: "addition works correctly",
  fn: () => {
    const result = 2 + 3;
    assertEquals(result, 5);
  }
});
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

Forgetting to import assertion functions like assertEquals causes errors because Deno.test itself does not provide assertions.

Not marking async tests properly can cause tests to finish before async code runs. Use async keyword if your test uses await.

Using Deno.test without a name makes it harder to identify tests in output.

typescript
/* Wrong: missing import and async handling */
Deno.test({
  name: "async test without await",
  fn: () => {
    setTimeout(() => {
      // test code
    }, 100);
  }
});

/* Right: import assertion and async function */
import { assert } from "https://deno.land/std@0.203.0/testing/asserts.ts";

Deno.test({
  name: "async test with await",
  async fn() {
    await new Promise((r) => setTimeout(r, 100));
    assert(true);
  }
});
๐Ÿ“Š

Quick Reference

  • Deno.test: Defines a test with name and fn.
  • Assertions: Use from std/testing/asserts.ts like assertEquals, assert.
  • Run tests: Use deno test in terminal.
  • Async tests: Mark fn as async if using await.
โœ…

Key Takeaways

Use Deno.test with a descriptive name and a function containing test code.
Import assertion functions from Deno's standard library to check results.
Mark test functions async if they use await to handle asynchronous code.
Run tests using the command 'deno test' in your terminal.
Always give your tests clear names to identify them easily in output.