How to Run Tests in Deno: Simple Guide with Examples
To run tests in Deno, write test functions using
Deno.test() and then run deno test in your terminal. This command automatically finds and executes all test cases in your project files.Syntax
The basic syntax to define a test in Deno uses the Deno.test() function. It takes a test name and a function that contains your test code.
- Deno.test(name, fn): Defines a test where
nameis a string describing the test, andfnis a function with the test logic. assertfunctions fromstd/testing/asserts.tshelp check conditions inside tests.- Run tests by executing
deno testin the terminal, which finds all tests and runs them.
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 shows a simple test that checks if adding two numbers equals the expected result. Running deno test will execute this test and show if it passed or failed.
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
Some common mistakes when running tests in Deno include:
- Not importing assertion functions like
assertEquals, causing errors inside tests. - Forgetting to run tests with
deno testand trying to run test files withdeno runinstead. - Not using
asyncwhen testing asynchronous code, which can cause tests to pass incorrectly or hang.
Always use deno test to run tests and import asserts from the standard library.
typescript
import { assertEquals } from "https://deno.land/std@0.203.0/testing/asserts.ts"; // Wrong: missing assert import Deno.test("wrong test", () => { const result = 2 + 2; // assertEquals not imported, this will cause error // assertEquals(result, 4); }); // Right: Deno.test("correct test", () => { const result = 2 + 2; assertEquals(result, 4); });
Quick Reference
| Command or Function | Description |
|---|---|
| Deno.test(name, fn) | Defines a test with a name and test function |
| deno test | Runs all tests in the current directory and subdirectories |
| assertEquals(actual, expected) | Checks if two values are equal in a test |
| --allow-net | Flag to allow network access if your tests need it |
| --unstable | Flag to enable unstable Deno APIs if needed in tests |
Key Takeaways
Use Deno.test() to define tests and deno test to run them.
Import assertion helpers like assertEquals from Deno's standard library.
Run tests with deno test, not deno run.
Use async functions in tests when testing asynchronous code.
Add necessary permissions flags if your tests require them.